为什么在这个例子中 window.getSelection() 的焦点在 Chrome 中不起作用?
Why doesn't window.getSelection() on focus work in Chrome in this example?
我正在尝试使用 window.getSelection() 来 return 当一个 contenteditable 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) 中测试。
我正在尝试使用 window.getSelection() 来 return 当一个 contenteditable 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) 中测试。