检测codemirror编辑器的焦点

时间:2017-02-15 23:00:30

标签: javascript jquery html css codemirror

我在我正在创建的webapp中使用codemirror,并且我在页面上有几个编辑器。还有撤消和重做按钮,它们可以工作。但是我只能设置一个编辑器来撤消,除非我使用if语句来确定哪一个被聚焦,然后将撤消或重做功能应用到其相应的文本框。我在jQuery和JavaScript中尝试了一些变体,但无济于事。这是我试图开始工作的代码块之一。保存代码镜像设置的实际变量称为" codeeditor1","#editor1"是文本框的ID。

if ($("#editor1").is(':focus')) {
  undo.addEventListener('click', function() {
      codeeditor1.undo();
  }, false);
  redo.addEventListener('click', function() {
      codeeditor1.redo();
  }, false);
}

我也根据方法的文档尝试了这个" cm.hasFocus()" =布尔值。

if (codeeditor1.hasFocus() == true) {
    undo.addEventListener('click', function() {
        codeeditor1.undo();
    }, false);
    redo.addEventListener('click', function() {
        codeeditor1.redo();
    }, false);
}

我现在也尝试了这个,为了逻辑代码放置,但仍然没有运气。也许这是codemirror方法中的一个错误?

undo.addEventListener('click', function() {
    if (codeeditor1.hasFocus() == true) {
        codeeditor1.undo();
    }
}, false);

redo.addEventListener('click', function() {
    if (codeeditor1.hasFocus() == true) {
        codeeditor1.redo();
    }
}, false);

2 个答案:

答案 0 :(得分:1)

尝试

  if( editor.hasFocus() == true  ) 
      // This editor is Codemirror object 
      // not jquery element.
  }

答案 1 :(得分:0)

好!所以,我明白了。

问题是(我没想到),当用户按下按钮时,焦点会被移除,然后它会尝试测试它,这意味着“hasFocus”的结果当然是假的。所以为了解决这个问题,我创建了一个变量。当其中一个编辑器聚焦到1,2或3时,变量会更新。然后我检查单击按钮的变量值是什么,然后在运行任一撤消之前将焦点重新应用到相应的编辑器或重做现在的焦点编辑器。

var detectfocus = "0";

codeeditor1.on('focus', function() {
    detectfocus = "1";
});
codeeditor2.on('focus', function() {
    detectfocus = "2";
});
codeeditor3.on('focus', function() {
    detectfocus = "3";
});


undo.addEventListener('click', function() {
    if (detectfocus === "1") {
        codeeditor1.focus();
        codeeditor1.undo();
    } else if (detectfocus === "2") {
        codeeditor2.focus();
        codeeditor2.undo();
    } else if (detectfocus === "3") {
        codeeditor3.focus();
        codeeditor3.undo();
    }
}, false);

redo.addEventListener('click', function() {
    if (detectfocus === "1") {
        codeeditor1.focus();
        codeeditor1.redo();
    } else if (detectfocus === "2") {
        codeeditor2.focus();
        codeeditor2.redo();
    } else if (detectfocus === "3") {
        codeeditor3.focus();
        codeeditor3.redo();
    }
}, false);
相关问题