开发者

Highlight/select multiple divs with ranges w/ contenteditable?

开发者 https://www.devze.com 2023-02-06 02:44 出处:网络
Let\'s s开发者_如何学运维ay I have a set of contenteditable=\"true\" divs. <div id=\"0\" contenteditable=\"true\"></div>

Let's s开发者_如何学运维ay 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号