输入元素上的 onClick 与 onFocus

Exp*_* be 5 html javascript jquery

为了在用户单击输入框时将焦点移到输入的末尾,我使用了这样的方法,

$(function() {
    $('#test-input').on('click', function(evt) {
    $target = $(evt.target);
    var val = $target.val();

    $target.val('').val(val);
  });
}())
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="test" id="test-input" value="abcdefgh" />
Run Code Online (Sandbox Code Playgroud)

但是,如果我将“点击”更改为“焦点”,则不起作用。

$(function() {
    $('#test-input').on('focus', function(evt) {
    $target = $(evt.target);
    var val = $target.val();

    $target.val('').val(val);
  });
}())
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="test" id="test-input" value="abcdefgh" />
Run Code Online (Sandbox Code Playgroud)

在这种情况下,onClick 和 onFocus 操作有何不同?

Cal*_*nes 6

有一些区别:

onClick:每当用户点击一个对象,比如一个按钮、一个图像、一个输入...

onFocus:这个事件在一个元素被选中时被触发,它不需要被点击,它可以通过编程来完成,例如调用.focus()或使用 Tab 键。此外,使用onfocus代替onclick,可以帮助避免冒泡

最后,使用下面的代码段(我添加了更多输入,使用 TAB 循环浏览它(或者也单击),您会看到插入符号将在所有之后结束。
为什么我添加了超时? Chrome 浏览器有一个奇怪的怪癖在光标移动到字段之前触发焦点事件的地方,因此,事件必须等待光标到达那里,然后再将其移动到最后。

$(function() {
  $('.test-input').on('focus', function(evt) {
    that = this;
    setTimeout(function() {
      that.selectionStart = that.selectionEnd = 10000;
    }, 1);
  });
}())
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="test" class="test-input" value="abcdefgh" />
<input type="text" name="test" class="test-input" value="a1b2c3" />
<input type="text" name="test" class="test-input" value="abcdefghijklmnop" />
Run Code Online (Sandbox Code Playgroud)


额外:如果你只是为手机编程,看看touchEventshttps://developer.mozilla.org/pt-BR/docs/Web/Events/touchstart)会很高兴