getSelection() 在 IE 中不起作用 [英] getSelection() not working in IE

查看:40
本文介绍了getSelection() 在 IE 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我让这段代码在 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);
});

在这里编码:http://jsfiddle.net/WdrC2/

提前致谢...

推荐答案

IE 9 之前不支持 window.getSelection().您可以改用 document.selection(请参阅 此 msdn 页面 的说明).这个选择对象有一个方法 createRange() 返回一个 TextRange 对象(见 此 msdn 页面 了解详情).

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).

请注意,selectiontextrange 对象都是微软自己的实现,并不遵循 W3C 标准.您可以在 www.quirksmode.org/dom/range_intro.html.

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.

以下实现适用于 IE:

The following implementation works in IE:

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

它几乎没有其他实现那么好,因为您必须使用字符串而不是 dom.有一个小技巧,您可以将 <span id="myUniqueId"></span> 作为占位符粘贴,然后使用 dom 替换它.不过,您仍然需要使用 range.htmlTextrange.text.

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.

顺便说一句:上面的实现显然只是 IE.您必须使用一些浏览器功能检测来决定使用哪个版本.

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

这篇关于getSelection() 在 IE 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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