Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

javascript - selection change event in contenteditable

My markup for contenteditable element is as below:

<iframe class="rich_text">
<html style="background:none transparent;">
    <head></head>
    <body contenteditable="true"></body>
</html>
</iframe>

Is there a selection change event for the body (contenteditable)? So that I can detect whether the selected text block has bold/underline etc.

I've tried some event handlers (jQuery) but without success:

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() { ... });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no cross-browser way of detecting changes to the selection. IE and recent WebKit browsers (Chrome and Safari, for example) support a selectionchange event on the document. Firefox and Opera have no such event and all you can do is detect selection changes made via keyboard and mouse events, which is unsatisfactory (there is no way of detecting "Select All" from context or edit menus, for example).

Update 2017: There is now a cross-browser way. Recent WebKit/Blink browsers (Chrome, Safari, Opera) support selectionchange, and Firefox supports it since version 43.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...