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

查看:405
本文介绍了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/

提前致谢...

推荐答案

9之前的IE不支持 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).

请注意,选择 textrange 对象都是微软有自己的实施,不遵循W3C标准。您可以在 textrange 和范围问题的更多信息。 org / dom / range_intro.htmlrel =noreferrer> 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:

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

它不像其他实现那么好,因为你必须使用字符串而不是dom。您可以将< span id =myUniqueId>< / span> 作为占位符粘贴,然后使用dom替换它。您仍然需要使用 range.htmlText range.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.

BTW:上面的实现显然只是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天全站免登陆