如何用元素包装/环绕突出显示的文本 [英] How To Wrap / Surround Highlighted Text With An Element

查看:75
本文介绍了如何用元素包装/环绕突出显示的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将选定的文本用span包裹在div容器中,可以吗?

I want to wrap a selected text in a div container with span, is it possible?

用户将选择一个文本并单击一个按钮,在按钮上单击事件,我想用span元素包装所选的文本。我可以使用 window.getSelection()获取所选文本,但是如何知道其在DOM结构中的确切位置?

A user will select a text and will click a button, on button click event I want to wrap that selected text with span element. I can get the selected text using window.getSelection() but how to know its exact position in DOM structure?

推荐答案

如果所选内容完全包含在单个文本节点中,则可以使用您从选择中获得的范围的 surroundContents() 方法。但是,这非常脆弱:如果选择不能在逻辑上包围在单个元素中(通常,如果范围跨越节点边界,则该选择不起作用,尽管这不是精确定义)。要在一般情况下执行此操作,您需要一种更复杂的方法。

If the selection is completely contained within a single text node, you can do this using the surroundContents() method of the range you obtain from the selection. However, this is very brittle: it does not work if the selection cannot logically be surrounded in a single element (generally, if the range crosses node boundaries, although this is not the precise definition). To do this in the general case, you need a more complicated approach.

此外,DOM Range 和<$ IE< c中不支持c $ c> window.getSelection()。 9.对于这些浏览器,您将再次需要另一种方法。您可以使用我自己的 Rangy 之类的库来规范浏览器行为,并且您可能会发现课程应用模块对此问题很有用。

Also, DOM Range and window.getSelection() are not supported in IE < 9. You'll need another approach again for those browsers. You can use a library such as my own Rangy to normalize browser behaviour and you may find the class applier module useful for this question.

简单的 surroundContents()示例jsFiddle: http:// jsfiddle.net/VRcvn/

Simple surroundContents() example jsFiddle: http://jsfiddle.net/VRcvn/

代码:

function surroundSelection(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(element);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}

这篇关于如何用元素包装/环绕突出显示的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆