Html 防止光标在文本输入上移动
我有一些文本输入,当它们处于焦点时,我调用JS函数。基本上,此函数更改此字段的值。 当我这样做时,在IE上,光标移动到输入的左端。这在Firefox中是不会发生的。它只是停留在我放在第一位的地方Html 防止光标在文本输入上移动,html,internet-explorer,input,Html,Internet Explorer,Input,我有一些文本输入,当它们处于焦点时,我调用JS函数。基本上,此函数更改此字段的值。 当我这样做时,在IE上,光标移动到输入的左端。这在Firefox中是不会发生的。它只是停留在我放在第一位的地方 <input maxlength="5" type="text" onFocus=\"changeValueOnFocus(this);\">"; function changeValueOnFocus(myInput){ myInput.value = 1234; } ”; 函数
<input maxlength="5" type="text" onFocus=\"changeValueOnFocus(this);\">";
function changeValueOnFocus(myInput){
myInput.value = 1234;
}
”;
函数changeValueOnFocus(myInput){
myInput.value=1234;
}
有没有办法避免这种情况?
谢谢!将光标移动到文本框的末尾 按如下方式修改您的函数:
function changeValueOnFocus(myInput) {
myInput.value = 1234;
//use this function to select text but in this case just to move cursor to the end
myInput.setSelectionRange(myInput.value.length, myInput.value.length);
}
将光标移动到文本框的末尾 按如下方式修改您的函数:
function changeValueOnFocus(myInput) {
myInput.value = 1234;
//use this function to select text but in this case just to move cursor to the end
myInput.setSelectionRange(myInput.value.length, myInput.value.length);
}
不要使用
onfocus
,而是使用onfocusin
,这样可以使代码正常工作
编辑
我刚刚意识到,Firefox中没有focusin
,因此你需要更重的东西
剧本:
function changeValueOnFocus (e, elm) {
elm = elm || this;
elm.value = 1234;
return;
}
window.onload = function () {
if (window.onfocusin === undefined) {
document.getElementById('someinput').addEventListener('focus', changeValueOnFocus, false);
}
return;
}
对于输入
,您需要一个id
:
<input id="someinput" maxlength="5" onfocusin="changeValueOnFocus(event, this);" type="text" />
现在,这应该是一个跨浏览器的解决方案。而不是
onfocus
,而是使用onfocusin
,这将使您的代码正常工作
编辑
我刚刚意识到,Firefox中没有focusin
,因此你需要更重的东西
剧本:
function changeValueOnFocus (e, elm) {
elm = elm || this;
elm.value = 1234;
return;
}
window.onload = function () {
if (window.onfocusin === undefined) {
document.getElementById('someinput').addEventListener('focus', changeValueOnFocus, false);
}
return;
}
对于输入
,您需要一个id
:
<input id="someinput" maxlength="5" onfocusin="changeValueOnFocus(event, this);" type="text" />
现在,这应该是一个跨浏览器的解决方案