mousedown event中保持input的focus状态

Published: · LastMod: June 01, 2023 · 168 words

mousedown event中保持input的focus状态 🔗

一定要使用e.preventDefault去除默认失去焦点行为

1
2
3
  <input>

  <button>CLICK</button> <button>MOUSEUP</button> <button>MOUSEDOWN</button> <button>MOUSEDOWN 2</button>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
document.querySelector('button').addEventListener('click', function () {
  document.querySelector('input').focus();
}, false);

document.querySelectorAll('button')[1].addEventListener('mouseup', function () {
  document.querySelector('input').focus();
}, false);

document.querySelectorAll('button')[2].addEventListener('mousedown', function (e) {
  document.querySelector('input').focus();
}, false);

document.querySelectorAll('button')[3].addEventListener('mousedown', function (e) {
  document.querySelector('input').focus();
  e.preventDefault();
}, false);

reference 🔗

https://codepen.io/impressivewebs/pen/qBNLqWN?editors=1000