使用span封装选定的文本节点 [英] Wrapping a selected text node with span

查看:84
本文介绍了使用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 范围 window.getSelection()不支持在IE<您将需要再次为这些浏览器提供另一种方法。您可以使用我自己的 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);
        }
    }
}

这篇关于使用span封装选定的文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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