jQuery将光标设置为焦点输入字段的开头 [英] jQuery Set Cursor to Beginning of Input Field on Focus

查看:72
本文介绍了jQuery将光标设置为焦点输入字段的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段<input value="@website.com" type="text" name="email" id="email">,我想输入一个字段,以便当用户专注于此字段时,它将把光标移动到@website.com之前.

I have an input field <input value="@website.com" type="text" name="email" id="email"> and I want to make it so when a user focuses on this field, it will move the cursor to be before the @website.com.

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

I have the following Javascript/jQuery code but it does not seem to work:

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

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

It seems like the .focus() keeps calling the focusin() function.

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

I know $("#email")[0].setSelectionRange(0,0); is the proper way to move the cursor to the front but how do I bind it to when the field has focus?

所以当我使用时:

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

当我进入该字段时,它将光标设置为开始处,但是当我单击该字段时,它不会将其设置为开始处.

It sets the cursor to the beginning when I tab into the field but not when I click in.

Edit2:这与在此处输入链接描述不同,因为这只是获得插入符位置,而我正在设置插入符位置.

This is different than enter link description here because that just gets the caret position whereas I am looking to set the caret position.

推荐答案

这会将输入字段的focusclick事件绑定到该函数.希望这会有所帮助!

This will bind the focus AND click events of the input field to the function. Hope this helps!

$('#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 ...

Or, without 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">

这篇关于jQuery将光标设置为焦点输入字段的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆