点击按钮,文本框如何不失去焦点

给按钮设置 mousedown 事件,并在其中 event.preventDefault() 就能够了javascript

// html
<input type="text" autofocus="autofocus">
<button>点击我文本输入框不会失去焦点</button>

// javascript
var btn = document.querySelector('button')
btn.onmousedown = function(event) {event.preventDefault()}

要点击按钮,触发按钮的 click 事件,但又不想触发 input 的 blur 事件。 这里面的问题就在于,当咱们点击按钮的时候,文本框失焦,这是浏览器的默认事件。当你点击按钮的时候,会触发按钮的 mousedown 事件,mousedown 事件的默认行为是使除了你点击的对象以外的有焦点的对象失去焦点。因此只要在 mousedown 事件中阻止默认事件发生就能够了!html

相关文章
相关标签/搜索