简体   繁体   中英

Highlight/select multiple divs with ranges w/ contenteditable?

Let's say I have a set of contenteditable="true" divs.

<div id="0" contenteditable="true"></div>
<div id="1" contenteditable..></div>
<div...etc></div>

I can't have one div, multiple divs is a must. How could I highlight the content of more than one div? Using ranges? Anything else?

The answer is that it depends on the browser. See this example for a test of two methods using Ranges. The first attempts to create a Range per editable <div> and add all of them to the selection. The second attempts to create a single Range encompassing the contents of two editable <div> s.

Results:

  • In all browsers, it is impossible for the user to create a selection that lives in more than one editable element;
  • Firefox is the most permissive of the major browsers. Both programmatic methods work.
  • Safari and Chrome is the least permissive: neither method selects content from more than one editable element.
  • Opera 11 does not support multiple Ranges in the selection, but does support a selected Range spanning more than one editable element.
  • IE pre-version 9 does not support DOM Range or the same Selection API as other browsers, but the equivalent TextRange code does not allow selection from more than one editable element.

It is possible to switch the divs to contenteditable="false" on the fly as a consequence of starting a selection in one of them. Something like this gives you the idea (using JQuery):

$('div').bind("selectstart", function() {
    $('div').attr("contenteditable", false);
});​

Here's a fiddle to demonstrate (only tested in Chrome).

Note in the fiddle example that the first ContentEditable Div gets the focus. This allows you to type away as normal, but as soon as you select anything, using mouse or keyboard, you'll see you can extend the selection across divs as usual.

This obviously needs fleshing out to work with multiple browsers and to turn back to contenteditable="true" appropriately. But I think the approach is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM