1

您能帮我理解为什么正在检索焦点的 div 将光标放在 Firefox 和 IE 10 上的第一个字符上(但不在 chrome 上)?

这是javascript代码:

$('div').on('click', function(e) {
    $(this).html($(this).text());
});

这是jsfiddle整个上下文。

[编辑]有人能告诉我为什么光标会到句子的开头吗?

4

2 回答 2

3

行为差异:

那是因为当你传递相同/精确的内容时,Chrome 不会认为内容会发生变化,但 FF/IE 并不关心内容是否相同;如果有任何通过,他们认为它已被修改。不同的浏览器引擎并不总是以相同的方式运行。

$('div').on('click', function(e) {
    $(this).html($(this).text()); // here you pass the same (previous) content
});

查看浏览器(Chrome 或 FF)是否将此解释为“内容已更改”;您可以收听该DOMSubtreeModified事件。这不会在 Chrome 上触发,但会在 FF 上触发。

$('div').on('DOMSubtreeModified', function(e) {
    console.log('content changed');
});

现在,如果你“真的”通过传递一个“新”值来改变内容;Chrome 的行为也与 FF 相同。例如,试试这个:

$('div').on('click', function(e) {
    $(this).html($(this).text() + "new content"); // passing different content each time
});

现在,您将看到该DOMSubtreeModified事件已被触发。

为什么光标移动到开头:

那是因为; 当用户单击 时div,他/她实际上将光标设置到某个位置/索引。然后您立即更改全部内容;因此在替换内容时位置/索引不再可用。当时唯一有效的位置是 0(开始索引)。

如果通过 bec 传递相同的内容,则在 Chrome 中不会发生这种情况。(正如先前所说); 如果内容与之前的内容相同,Chrome 不会替换该内容。所以游标索引永远不会改变。但是,如果您确实传递了不同的内容;它还将光标移动到开头。


这是测试的小提琴DOMSubtreeModified

于 2013-05-31T01:11:58.947 回答
0

The issue is that IE and Firefox have a different implementation of contentEditable. This means that, when clicked, they select the first element within the editable area.

You can get around this issue by using some code like the following:

var char = 3, sel; // character at which to place caret
content.focus();
if (document.selection) {
  sel = document.selection.createRange();
  sel.moveStart('character', char);
  sel.select();
}
else {
   sel = window.getSelection();
  sel.collapse(content.firstChild, char);
}

However, what I'd recommend is using something like TinyMCE or CKEditor or a JQuery/JQueryUI editor to get the desired effect.

Plus, you get the nice formatting tools too!

于 2013-05-30T08:59:26.030 回答