我正在尝试使用 window.getSelection() 在聚焦可内容编辑的 div 时返回节点。
html:
<div id="testing" contenteditable="true">
<p>Click on me while monitoring the console</p>
</div>
jQuery:
$('#testing').focus(function() {
console.log(window.getSelection());
});
在这里查看 JSFiddle:http://jsfiddle.net/yftf24g6/
监控控制台,我在 Firefox 中获得文本节点选择,但在 Chrome 中没有(选择 {type: "None"})
谁能解释一下为什么?
最佳答案
在 chrome 中(如我所见)在完成选择之前,只要单击可编辑元素,就会触发 focus
事件。添加 setTimeout
可以解决问题,但这是一种不可靠的 hack。
我建议你使用 mouseup
事件,
The mouseup event is sent to an element when the mouse pointer is over the element, and the mouse button is released. Any HTML element can receive this event.
$('#testing').mouseup(function() {
console.log(window.getSelection().toString());
});
在 Firefox(37.0.2) 和 Chrome(42.0.2311) 中测试。
关于javascript - 在此示例中,为什么 window.getSelection() on focus 在 Chrome 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30135936/