javascript - 在此示例中,为什么 window.getSelection() on focus 在 Chrome 中不起作用?

标签 javascript jquery google-chrome firefox

我正在尝试使用 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) 中测试。

Updated Fiddle

关于javascript - 在此示例中,为什么 window.getSelection() on focus 在 Chrome 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30135936/

相关文章:

javascript - 如何在 JavaScript 中创建 JSONArray 的子弹图?

javascript - 无法在 IE 中将函数从一个窗口传递到另一个窗口

javascript - 有没有办法阻止 contenteditable 插入符号出现在 IE 10 中的元素上?

asp.net - 使用 jQuery 将 ASP.NET 控件添加到页面

javascript - 从 JQuery 创建 iframe - 属性不起作用,为什么不呢?

javascript - Chrome devtools 显示未定义,但值在飞出时存在

javascript - 当我在 chrome 控制台上使用函数时,我得到了 undefined

javascript - 从回调访问 polymer 组件属性?

jquery - 使用 jQuery/AJAX 解码 JSON

google-chrome - Chrome : find out WHEN a page was loaded