Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...