Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - getSelection() not working in IE

Can someone help me get this code working in IE please:

HTML:

<p>Alex Thomas</p>
<button id="click">Click</button>

JS

$('#click').click(function(){
    var range = window.getSelection().getRangeAt(0);
    var selectionContents = range.extractContents();
    var span = document.createElement("span");
    span.style.color = "red";
    span.appendChild(selectionContents);
    range.insertNode(span);
});

Coded up here: http://jsfiddle.net/WdrC2/

Thanks in advance...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IE prior to 9 doesn't support window.getSelection(). You can use document.selection instead (see this msdn page for the description). This selection object has a method createRange() that returns a TextRange object (see this msdn page for details).

Note that both the selection and textrange objects are Microsofts own implementation and do not follow the W3C standards. You can read more about the textrange and range issues on www.quirksmode.org/dom/range_intro.html.

The following implementation works in IE:

$('#click').click(function(){
    var range = document.selection.createRange();
    range.pasteHTML("<span style='color: red'>" + range.htmlText + "</span>");
});

It's not nearly as nice as the other implementation since you have to work with strings instead of the dom. There is a little hack where you paste <span id="myUniqueId"></span> as a placeholder, and afterwards replace it using the dom. You still have to work with range.htmlText or range.text though.

BTW: the above implementation is obviously IE only. You have to use some browser capability detection to decide which version to use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...