参考自:
http://www.zhangxinxu.com/wordpress/2011/04/js-range-html%E6%96%87%E6%A1%A3%E6%96%87%E5%AD%97%E5%86%85%E5%AE%B9%E9%80%89%E4%B8%AD%E3%80%81%E5%BA%93%E5%8F%8A%E5%BA%94%E7%94%A8%E4%BB%8B%E7%BB%8D/
http://www.w3school.com.cn/xmldom/dom_range.asp
IE678支持 document.selection.createRange()
chrome,FF,opera,safari支持 window.getSelection()
虽然看起来效果差不多,但IE是Text Range对象,而在Mozilla、Safari、Opera下是个Selection对象。
一般是document.onmouseup设置该处理函数
document.onmouseup = function(){
//如果需要获取用户选择的文本
var userSelection = getSelection();
if(userSelection.text){//处理IE
userSelection = userSelection.text;
}
alert(userSelection.toString());
}
function getSelection(){
if(window.getSelection){
return window.getSelection();
}else{
return document.selection.createRange();
}
}
如果需要消除选择的文本,比如防止误选操作,可以这样写:
IE: document.selection.empty()
other: window.getSelection().removeAllRanges()
如果想创建和Selection对象内容一样的Range对象,可以这样:
var getRangeObject = function(selectionObject) {
if (selectionObject.getRangeAt){
return selectionObject.getRangeAt(0);
}else{ // 较老版本Safari!
var range = document.createRange();
range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
return range;
}
}
var rangeObject = getRangeObject(userSelection);
本文详细介绍了在不同浏览器中使用JavaScript获取用户选择文本的方法,包括如何在IE678中使用document.selection.createRange(),以及在Mozilla、Safari、Opera等浏览器中使用window.getSelection()。同时提供了消除选择文本和创建与Selection对象内容一致的Range对象的方法。
1万+

被折叠的 条评论
为什么被折叠?



