function getSelectedText() {
var txt = "";
if (document.selection) {
//ie8 非标准状态下面
txt = window.document.selection.createRange().text
}else{
// ie11 chrome ff window.getSelection|| document.getSelection
txt = window.getSelection()||window.document.getSelection();
}
return txt;
}
var o = document.getElementById('editor');
var win = o.contentWindow;
var doc = o.contentDocument||o.contentWindow.document;// 以上写法在第一篇博文有介绍过,主要是为了兼容什么来着 ?_-_?
function getSelectedText() {
var txt = "";
if ( document.selection ) {
txt = doc.selection.createRange().text;
}else{
txt = win.getSelection()|| doc.getSelection();
}
return txt;
}
详 细介绍这个属性,就不在做兼容说明,所有兼容是基于前面说过的写法雷同,document.selection 介绍
document.selection 表示当前网页中的选中内容。代表了当前激活选中区,即高亮文本块,和/或文档中用户可执行某些操作的其它元素。 selection对象的典型用途是作为用户的输入,以便识别正在对文档的哪一部分正在处理,或者作为某一操作的结果输出给用户。
主要使用的方法有:
- clear() 清除选中的内容
- empty() 取消选中
- createRange() 返回 TextRange 这个方法看着是不是很眼熟,对上一篇中有一个 createTextRange,这两个到底是什么渊源?
对象或元素不同,虽然都是返回TextRange。例如:
var r= document.body.createTextRange()
var r= document.createRange()
createTextRange 可以对body、TEXTAREA、BUTTON创建 TextRange。
-------来自百度知道团队的 temp_1018 的精辟回答
属性有:
- type 选中内容的类型
- typeDetail 不支持
【未完,待续】function setLocation(elm, n) {
if(n > elm.value.length)
n = elm.value.length;
if(elm.createTextRange) { // IE
var textRange = elm.createTextRange();
textRange.moveStart('character', n); // 也可以是 rng.move("character",n);textRange.collapse();
textRange.select();
} else if(elm.setSelectionRange) { // Firefox
elm.setSelectionRange(n, n);
elm.focus();
}
}