【问题标题】:jQuery Set Cursor to Beginning of Input Field on FocusjQuery 将光标设置为焦点上输入字段的开头
【发布时间】:2018-07-11 22:06:53
【问题描述】:

我有一个输入字段<input value="@website.com" type="text" name="email" id="email">,我想这样当用户关注这个字段时,它会将光标移动到@website.com之前。

我有以下 Javascript/jQuery 代码,但它似乎不起作用:

$(document).ready(function() {
    $("#email").focusin(function(){
        $("#email").focus();
        $("#email")[0].setSelectionRange(0,0);
    });
});

似乎.focus() 一直在调用focusin() 函数。

我知道$("#email")[0].setSelectionRange(0,0); 是将光标移到前面的正确方法,但是当字段有焦点时如何将其绑定到?

编辑:所以当我使用时:

$("#email").focus(function(){
    $("#email")[0].setSelectionRange(0,0);
});

当我进入字段时它会将光标设置为开头,但当我单击时不会。

Edit2:这与 enter link description here 不同,因为它只是获取插入符号的位置,而我正在寻找插入符号的位置。

【问题讨论】:

  • 如果你和console.log() 在上面的$("#email").focus(); 之前检查控制台,你会看到你正在通过.focus 创建无限循环,因为focusin 事件触发,结果在maximum call stack size exceeded 错误中。
  • 首先...$("#email")[0] 是可憎的。你强制 jQuery 创建一个对象......然后你使用它的[0],它与document.getElementById("#email") 相同。有关添加到 jQuery 对象中的这个元素的更多信息,请公开它。 -- 所以这在语法上是一个“doh!”
  • 在我上面的评论中,you disclose it.应该是you discard it.;)

标签: javascript jquery focus


【解决方案1】:

这会将输入字段的focus AND click 事件绑定到函数。希望这会有所帮助!

$('#email').on('focus click', function() {
  $(this)[0].setSelectionRange(0, 0);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Enter your name" autofocus>
<input type="text" id="email" value="@website.com">

或者,没有 jQuery...

document.getElementById('email').addEventListener('click', moveCursor);
document.getElementById('email').addEventListener('focus', moveCursor);

function moveCursor(event) {
   event.target.setSelectionRange(0, 0);
}
<input type="text" placeholder="Enter your name" autofocus>
<input type="text" id="email" value="@website.com">

【讨论】:

  • 那行得通。做得好。顺便说一句,你可以改用$(this)[0].setSelectionRange(0,0);
  • 啊,真的。谢谢!
【解决方案2】:

你真的需要 jQuery 吗?

document.getElementById("email").addEventListener("click", moveCursor);
document.getElementById("email").addEventListener("focus", moveCursor);

function moveCursor(event) {
    event.target.setSelectionRange(0,0);
}
&lt;input value="@website.com" type="text" name="email" id="email"&gt;&lt;/input&gt;

【讨论】:

    【解决方案3】:

    无论你想用光标做什么,都需要一个字段焦点。

    这是我使用的一个旧块。我什至在一个子目录中将它命名为cursor.js...我猜它是从很多地方取来的。

    这是一个 get/set 光标位置。它需要一个 JS 元素。 .oO($(el)[0] 语法松散..)

    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
        // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
    var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
        // At least Safari 3+: "[object HTMLElementConstructor]"
    var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
    var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
    
    
    function GetCursorPos (field) {
    
      // Initialize
      iCaretPos = 0;
    
      if (isIE){
    
        // Set focus on the element
        field.focus();
    
        // To get cursor position, get empty selection range
        oSel = field.createTextRange();
    
        // Move selection start to 0 position
        oSel.moveStart('character', -field.value.length);
    
        // The caret position is selection length
        iCaretPos = oSel.text.length;
      }
    
      if (isChrome||isSafari){
        iCaretPos = field.selectionStart;
      }
    
      if (isFirefox){
        iCaretPos = field.selectionStart;
      }
    
      return iCaretPos;
    }
    
    function SetCursorPos (field,Pos) {
    
      // Set focus on the element
        field.focus();
    
      if (isIE){
        field.selectionStart=Pos;
      }
    
      if (isChrome||isSafari){
        field.setSelectionRange(Pos,Pos);
      }
    
      if (isFirefox){
        field.selectionStart=Pos;
      }
    
      return;
    }
    

    关于浏览器友好的考虑,有:

    1. .selectionStart -- Chrome/Safari/Firefox
    2. .setSelectionRange(Pos,Pos) -- Chrome/Safari/Firefox/Internet Explorer
    3. .createTextRange() -- Internet Explorer


    我很久以前在上面使用的灵感:partial (compared to the above) SO answer

    【讨论】:

    • 感谢您的评论。已更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 2011-01-08
    相关资源
    最近更新 更多