title: JavaScript操控光标,你会么? categories:
var getObj = function ( id ) {
//获取对象
var ele = document.getElementById(id);
//返回结果
return {
element: ele,
startPos: 0,
endPos: 0,
init: function(){
var _this = this;
if( !("__proto__" in {}) ){
this.element.attachEvent("onmouseup", _this.getPos);
}else{
this.element.addEventListener("mouseup", _this.getPos, false);
}
return this;
},
getPos: function () {
var _this = this;
if( document.selection ) {
try{
var range = document.selection.createRange();
var drange = range.duplicate();
drange.moveToElementText( _this.element );
drange.setEndPoint( "EndToEnd", range );
this.startPos = drange.text.length - range.text.length;
this.endPos = this.startPos + range.text.length;
}catch(e){
}
}else if( window.getSelection ){
try{
this.startPos = this.element.selectionStart;
this.endPos = this.element.selectionEnd;
}catch(e){
//throw new Error("getPos error");
}
}
return this;
},
setPos: function ( m, n ) {
var arg2 = n || m;
if( document.selection ) {
var range = document.selection.createRange();
range.collapse(true);
range.moveEnd('character', arg2);
range.moveStart('character', m);
this.element.focus();
}else if( window.getSelection ){
this.startPos = this.element.selectionStart = m;
this.endPos = this.element.selectionEnd = arg2;
this.element.focus();
}
},
getStr: function( m, n ){
this.getPos( m, n );
return this.element.value.toString().slice(this.startPos, this.endPos);
}
};
};
<p>很受伤,下次接着弄。<em>你也可以试试哈~</em></p>
<p>函数调用方式:</p>
<p>1. 初始化init()</p>var t = getObj("box").init();
<p>2. setPos()</p>//选中从m到n之间的内容
t.setPos(m, n);
//一个参数就是设置光标位置
t.setPos(m);
<p>3. getPos()</p>//这个算是一个内置函数,每次选择都自动调用了,可以不管
t.getPos();
<p>4. getStr()</p>//获取选中的字符串
t.getStr();
<p>5. invoke()</p>//执行你送入的函数
function yourFun(){}
//这个方法还没加进去,感觉用处也不大,原理就是使用call
t.invoke(yourFun);
<p>主要是不很了解IE的API,纠结了半天,又不愿意去看别人写的文档,先晾在这里,下次不全~</p>
<p><strong>本文未完,待续...</strong></p>