javascript - Firefox 中范围广泛、内容可编辑的插入符定位和焦点

标签 javascript jquery rangy

我正在尝试使用Rangy将光标定位在 contenteditable div 中,但我发现跨浏览器的行为不一致(这很奇怪,考虑到这被大力吹捧为“跨浏览器解决方案”) .

当我打开this fiddle时在 Chrome 36.0.1985.143 m 中,我观察到,在我点击的任何位置(在页面的“结果”部分内),选择都会更新,并且蓝色 div 会获得绿色边框。

但是;在 Firefox 31 中访问将在第 2 步之后定位插入符号,但不会移动绿色边框...并且在第 3 步之后,根本不会定位插入符号。

我的问题:

无论“当前”选择/焦点是什么,如何可靠地设置 contenteditable div 中插入符号的位置?

示例屏幕截图:

Example Screenshot

HTML:

<div id="msg">Every 2 seconds, a setInterval fires that tells rangy to set the selection to the firstChild (ie: text node) of the blue div at index 49 (between the second 2 arrows).</div>
  <ol>
    <li><span>Click the blue div, between the first 2 arrows, watch to see rangy reposition the caret.</span></li>
    <li><span>Click the red div, between the arrows, watch to see rangy reposition the caret. (Doesn't also move focus in Firefox 31 ?!?)</span></li>
    <li><span>Click this list right here.</span></li>
    <li><h4>DOES THE CARET REPOSITION?!?!</h4></li>
</ol>

<br />
<div contenteditable="true" id="one">CLICK HERE --><--  RANGY WILL REPOSITION HERE --><--</div>
<br />
<div contenteditable="true" id="two">CLICK HERE --><--</div>

CSS:

div#one {
  color: white;
  background-color: #00f;
}
div#two {
  color: white;
  background-color: #f00;
}
div#msg {
  background-color: #ccc;
  padding: 10px;
}

:focus {
  border: 2px solid lime;
  padding: -2px;
}

JS:

setInterval(function () {
  rangy.getSelection().collapse($('#one')[0].firstChild, 49);
}, 2000);

最佳答案

Rangy 不会自动处理焦点,就像 native 浏览器选择 API 不处理焦点一样。你需要自己做。在这种情况下,只需调用可编辑元素的 focus() 方法即可:

setInterval(function () {
  var editableOne = $('#one')[0];
  editableOne.focus();
  rangy.getSelection().collapse(editableOne.firstChild, 49);
}, 2000);

演示:http://jsfiddle.net/afvc7r6r/2/

关于javascript - Firefox 中范围广泛、内容可编辑的插入符定位和焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25517914/

相关文章:

javascript - 音乐结束时自动播放新的音频文件

javascript - 如何使用 Angular 或 jquery 限制复选框选择

javascript - jQuery 图像和 if/else 语句

javascript - 移动到最后一个带有 rangy 的字符

javascript - 具有重叠文本范围的解决方案。

rangy:执行尽可能最小的扩展,以便 canSurroundContents() = true

javascript - 控制 Roku 盒子的脚本不起作用

javascript - 如何在每次加载时更改背景图像

javascript - 使用 li :hover is not showing div when the list item is an anchor

javascript - jQuery 函数在回调时不返回任何内容