开发者

javascript - how to wrap text blocks in <span> containing html tags in IE

I'm unable t开发者_StackOverflow社区o figure this out in Internet Explorer, but I want to be able to wrap a text block with tags that contain various html tags in it. I am writing a highlighting function where you highlight text with your mouse and the selection you highlight is wrapped in a <span> tag. For example, consider the following text block (as input):

<p>Lorem <i><b>ipsum dolor</b> sit amet</i>, consectetur <b>adipiscing elit</b>. Morbi</p>
<p></p>
<p>mperdiet, augue id sagittis porta, leo leo...</p>

I want the output to be (if you were to highlight the entire thing):

<p><span class='id1 highlight'>Lorem </span><i><b><span class='id1 highlight'>ipsum dolor</span></b><span class='id1 highlight'> sit amet</span></i><span class='id1 highlight'>, consectetur </span><b><span class='id1 highlight'>adipiscing elit</span></b><span class='id1 highlight'>. Morbi</span></p>
<p></p>
<p><span class='id1 highlight'>mperdiet, augue id sagittis porta, leo leo...</span></p>

(and highlight could be something like: .highlight{background-color:yellow} for example)

I'm retrieving the string by using: htmlStr = document.selection.createRange().htmlText;

The best I can figure out so far is to use:

document.selection.createRange().pasteHTML( "<span class='id1 highlight'>" + htmlStr + "</span>" );

edit: I also want to assign another class to the highlight for tracking purposes (id1 in this case).


This is tricky to achieve in the general case (think of selections crossing element boundaries: a single <span> cannot be used to surround such a selection). You can use document.execCommand() to do this in all major browsers. See my answer to a similar question here: How can I highlight the text of the DOM Range object?

UPDATE

To wrap the whole selection in <span>s with a particular class, you could use the CSS class applier module of my Rangy library. It works in all major browsers. However, each applier object only deals with one class, so you'll need to use two for your case. Example code:

<script type="text/javascript">
    var highlightApplier, idApplier;

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

    function toggleHighlight() {
        highlightApplier.toggleSelection();
        idApplier.toggleSelection();
    }
</script>

<input type="button" value="Toggle highlight"
    onclick="toggleHighlight();">
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜