选择改变事件在contenteditable

Yon*_*Fei 6 javascript jquery

我对contenteditable元素的标记如下:

<iframe class="rich_text">
<html style="background:none transparent;">
    <head></head>
    <body contenteditable="true"></body>
</html>
</iframe>
Run Code Online (Sandbox Code Playgroud)

是否有身体的选择更改事件(contenteditable)?这样我就可以检测所选文本块是否有粗体/下划线等.

我尝试了一些事件处理程序(jQuery),但没有成功:

var richText = $(".rich_text"),
richTextDoc = richText.contents()[0],
richTextBody = richText.contents().find("body");

// Enable Design mode.
richTextDoc.open();
richTextDoc.write("");
richTextDoc.close();
richTextDoc.designMode = "on";

// Binds selection change event
$(richTextDoc).bind("select", function() { ... });
$(richTextDoc).bind("selectstart", function() { ... });
richTextBody .bind("select", function() { ... });
richTextBody .bind("selectstart", function() { ... });
Run Code Online (Sandbox Code Playgroud)

Tim*_*own 6

没有跨浏览器方式来检测选择的更改.IE和最近的WebKit浏览器(例如Chrome和Safari)支持selectionchange文档上的事件.Firefox和Opera没有这样的事件,您只能检测通过键盘和鼠标事件进行的选择更改,这是不能令人满意的(例如,无法从上下文或编辑菜单中检测到"全选").

2017年更新:现在有一种跨浏览器的方式.最近的WebKit/Blink浏览器(Chrome,Safari,Opera)支持选择更改,Firefox从版本43开始支持它.

  • @Frodik:有一个开放的W3C错误来规范它:https://www.w3.org/Bugs/Public/show_bug.cgi?id = 13952.如果你大惊小怪,事情有时会有所改变,尽管那里的影响最大的是浏览器实施者. (2认同)

mam*_*moo 5

假设您的iframe内容来自同一个域,您可以使用:

$('.rich_text').contents()
  .find('body')
  .bind('selectstart', function(){});
Run Code Online (Sandbox Code Playgroud)

从这里可以看到,选择元素时会正确触发selectstart事件.

  • This also does not work when the selection changes with the keyboard (scrolling the caret with the arrow keys. (2认同)