如何使用html标签将window.getSelection()。getRangeAt(0)包含在文本中? [英] How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?

查看:404
本文介绍了如何使用html标签将window.getSelection()。getRangeAt(0)包含在文本中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从window.getSelection()。getRangeAt(0)中进行选择,并用HTML标签(例如'span'或'mark')包围它?我更喜欢直接的javascript或jQuery解决方案。



我可以使用alert输出所选文本,但还没有弄清楚如何用额外的标记来包围它。我已经看到很多关于选择运行execCommand的例子,但这不是我正在寻找的。

看到我的工作示例在 jsfiddle



任何想法?谢谢

解决方案

如果所选文本全部包含在单个文本节点中,可以使用 surroundContents() 方法的范围。然而,这在一般情况下不起作用。要做的是围绕< span> 中的范围内的每个文本节点。我的 Rangy 图书馆有这样做的一个模块,并且可以跨浏览器工作(IE< = 8本身不支持DOM范围)。



使用Rangy的示例代码:

 < style type =text / css> 
span.highlighted {
background-color:yellow;
}
< / style>
< script type =text / javascript>
var highlightApplier;

window.onload = function(){
rangy.init();
highlightApplier = rangy.createCssClassApplier(highlight,true);
};

函数applyHighlight(){
highlightApplier.applyToSelection();
}
< / script>


How do I take a selection from window.getSelection().getRangeAt(0) and surround it with an HTML tag such as 'span' or 'mark'? I prefer a straight javascript or jQuery solution.

I am able to output the selected text using alert, but have not yet figure out how to surround it with additional markup. I have seen many examples of running execCommand on the selection, but that is not what I'm looking for.

See my working example at jsfiddle

Any ideas? Thanks

解决方案

If the selected text is all contained within a single text node, you can use the surroundContents() method of the Range. However, that doesn't work in the general case. The thing to do is surround each text node within the Range in a <span>. My Rangy library has a module that does this and works cross-browser (IE <= 8 does not natively support DOM Range).

Example code using Rangy:

<style type="text/css">
    span.highlighted {
        background-color: yellow;
    }
</style>
<script type="text/javascript">
    var highlightApplier;

    window.onload = function() {
        rangy.init();
        highlightApplier = rangy.createCssClassApplier("highlighted ", true);
    };

    function applyHighlight() {
        highlightApplier.applyToSelection();
    }
</script>

这篇关于如何使用html标签将window.getSelection()。getRangeAt(0)包含在文本中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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