突出显示/选择多个带有内容可编辑范围的 div?
假设我有一组 contenteditable="true"
div。
<div id="0" contenteditable="true"></div>
<div id="1" contenteditable..></div>
<div...etc></div>
我不能有一个div,多个div是必须的。我如何突出显示多个div的内容?使用范围?还要别的吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案是这取决于浏览器。请参阅此示例,了解使用范围的两种方法的测试。第一个尝试为每个可编辑
创建一个范围,并将它们全部添加到选择中。第二个尝试创建一个包含两个可编辑
内容的单个 Range。
结果:
Selection
API,但等效的TextRange
代码不允许从多个可编辑元素中进行选择。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:
Selection
API as other browsers, but the equivalentTextRange
code does not allow selection from more than one editable element.在其中一个 div 中开始选择后,可以将 div 即时切换为
contenteditable="false"
。这样的东西给你的想法(使用JQuery):Here's a fiddle to demo(仅在Chrome中测试)。
请注意,在小提琴示例中,第一个 ContentEditable Div 获得焦点。这允许您像平常一样打字,但是一旦您使用鼠标或键盘选择任何内容,您就会看到可以像往常一样在 div 之间扩展选择。
这显然需要充实以与多个浏览器一起使用并适当地返回到
contenteditable="true"
。但我认为这个方法是有效的。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):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.另一种解决方案是打开父元素的
contentaditable
,而不是在每个子元素上将其关闭。Another solution is to turn on the
contentaditable
of the parent element instead of turning it off on each child.