不要使用原生的setSelectionRange函数,而是使用这个函数:
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
var isChrome = !!window.chrome && !!window.chrome.webstore;
if (isChrome){
input.style.textIndent = "-1000px";
input.onblur =function(){
input.style.textIndent = "0px";
};
window.setTimeout(function() {
input.setSelectionRange(selectionStart, selectionEnd);
}, 0);
}else
input.setSelectionRange(selectionStart, selectionEnd);
}else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
实际上,兼容性问题是在Chrome 39中修复的一个
错误。因此,不需要:
input.onclick = function (){
this.setSelectionRange(this.value.length,this.value.length )
}
你将使用:
input.onclick = function (){
setSelectionRange(this,this.value.length,this.value.length )
}
这是我测试过的fiddle。