开发者

in Internet Explorer, pasteHTML causes unexpected behavior?

开发者 https://www.devze.com 2022-12-16 18:50 出处:网络
I have the following HTML w/Javascript code (note: this only works in Internet Explorer): <script type=\'text/javascript\'>

I have the following HTML w/Javascript code (note: this only works in Internet Explorer):

<script type='text/javascript'>
function changeIt() {
 var开发者_开发知识库 startTag = "<span class='h' id='123abc'>";
 var endTag = "</span>";
 var htmlStr = document.selection.createRange().htmlText;

 document.selection.createRange().pasteHTML(startTag + htmlStr + endTag);
}
</script>
<style type='text/css'> .h { background: yellow; }</style>
<p><b>Four</b> score and seven years</p>
<input type='button' value='change' onclick='javascript:changeIt();'>

To use this function, simply highlight any part of the text you see in the screen, then click the "Change" button. Now, the strange behavior:

If you highlight the word "Four" (with the bold tags) with anything else after the Four, it will make the entire highlight bold, which is not what I want. In other words, if you highlight with your mouse:

Four score and seven

then click the "change" button, it will output: Four score and seven

<b><span class='h' id='123abc'><b>Four</b> score and seven</span></b>

I would like it to output this instead: Four score and seven

<span class='h' id='123abc'><b>Four</b> score and seven</span>

What am I doing wrong? I'll take an answer in either Javascript or jQuery.

Note: seems the background color isn't show properly on here, but my point is the whole selection turns bold when I don't want it to.


If you're working with a TextRange, which you are in the example, you can use its built-in execCommand method for many formatting tasks. For the background colour example, it would be the following:

function changeIt() {
    document.selection.createRange().execCommand("BackColor", false, "yellow");
}

Note: this example is IE only.

0

精彩评论

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