chrome下设置光标位置
代码如下:
<input id="hidenTag" type="hidden">
<input class="long-input" style = "width:350px" type="text" name="tags" value="" id="tags" onfocus="clearInterval(auto);"
onkeyup="$('#hidenTag').val(getCursorPosition(this));value=value.replace(/,/g,',');setCursorPosition(this,$('#hidenTag').val())"
onblur="value=value.replace(/,{2,}/g,',');">
<a href="javascript:;" onclick="javascript:funQieci();">获取TAG分词</a>
在一个内部CMS中,会自动根据相关条件做分词处理,个别时候允许人工干预(就是手工设置tag分词),问题随之而来,用户会中英文混用输入','和',' ,而且删除时可能会留下两个逗号,所以多了几个处理
onkeyup="value=value.replace(/,/g,',');onblur="value=value.replace(/,{2,}/g,',');"
上面的代码能有效处理中英文逗号和多个逗号,但是一个副作用就是chrome浏览器下每一次onkeyup,光标都会置于最后一个位置,导致用户不能制止的误删tag分词。 寻得javascript代码如下:
//控制鼠标光标相关
function getCursorPosition (obj) {//获取光标位置函数
var CaretPos = 0; // IE Support
if (document.selection) {
obj.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -obj.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (obj.selectionStart || obj.selectionStart == '0')
CaretPos = obj.selectionStart;
return (CaretPos);
}
function setCursorPosition(obj, pos){//设置光标位置函数
if(obj.setSelectionRange)
{
obj.focus();
obj.setSelectionRange(pos,pos);
}
else if (obj.createTextRange) {
var range = obj.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
原理就是每一次onkeyup获取当前光标位置,然后立马设置光标位置,但是setCursortPosition函数不能和getCursortPosition 套用,也就是不能这样使用
setCursorPosition(this,getCursorPosition(this))
所以采用一个隐藏的表单项传值 $('#hiddenTag'),进而每一次onkeyup先获取光标位置赋值到隐藏ID,然后执行过滤,然后设置光标位置,值为隐藏的ID的值。
鼠标广告js控制代码出处 http://www.js8.in/466.html