【问题标题】:prevent cursor moving on text input防止光标在文本输入上移动
【发布时间】:2012-11-22 16:37:51
【问题描述】:

我有一些文本输入,当它们处于焦点时我调用了一个 JS 函数。基本上这个函数改变了这个字段的值。 当我这样做时,在 IE 上,光标移动到我输入的左端。这在 Firefox 中不会发生。它只是停留在我最初放置的位置。

<input maxlength="5"  type="text" onFocus=\"changeValueOnFocus(this);\">";

function changeValueOnFocus(myInput){
  myInput.value = 1234;
}

有没有办法避免这种情况? 谢谢!

【问题讨论】:

    标签: html internet-explorer input


    【解决方案1】:

    而不是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;
    }
    

    对于input,您需要id

    <input id="someinput" maxlength="5" onfocusin="changeValueOnFocus(event, this);" type="text" />
    

    现在这应该是一个跨浏览器的解决方案。

    【讨论】:

      【解决方案2】:

      将光标移动到文本框的末尾 像这样修改你的函数:

           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);
      
       }
      

      【讨论】:

        猜你喜欢
        • 2018-05-20
        • 1970-01-01
        • 2020-02-25
        • 2013-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2011-11-08
        相关资源
        最近更新 更多