独角兽企业重金招聘Python工程师标准>>>
给按钮设置 mousedown 事件,并在其中 event.preventDefault() 就可以了
// html<input type="text" autofocus="autofocus"><button>点击我文本输入框不会失去焦点</button>// javascriptvar btn = document.querySelector('button')btn.onmousedown = function(event) {event.preventDefault()}
要点击按钮,触发按钮的 click 事件,但又不想触发 input 的 blur 事件。 这里面的问题就在于,当我们点击按钮的时候,文本框失焦,这是浏览器的默认事件。当你点击按钮的时候,会触发按钮的 mousedown 事件,mousedown 事件的默认行为是使除了你点击的对象之外的有焦点的对象失去焦点。所以只要在 mousedown 事件中阻止默认事件发生就可以了!