简体   繁体   English

如何在不分派“焦点”事件的情况下将焦点设置在输入元素上?

[英]How to set focus at an input element without dispatching the 'focus' event?

Following example code is provided in order to introduce the matter...提供以下示例代码以介绍该问题...

 const elm = document.getElementById('fname'); elm.addEventListener('focus', evt => console.log( `input element focused, event.type: "${ evt.type }"` ) ); elm.focus();
 <input type="text" id="fname" name="fname">

As one can see, the 'focus' event gets dispatched.可以看到, 'focus'事件被调度。 But I wish to focus the input element without dispatching this event.但我希望在不分派此事件的情况下关注输入元素。

Can this be done.这个可以吗。 And how would one achieve such behavior?以及如何实现这种行为?

The OP could register an initial 'focus' listener where the handler function's sole purpose is to immediately stop the passed event's propagation... evt.stopImmediatePropagation() . OP 可以注册一个初始'focus'侦听器,其中处理函数的唯一目的是立即停止传递的事件的传播... evt.stopImmediatePropagation() The downside is that no other handler of any later registered 'focus' listener can be executed.缺点是不能执行任何后来注册'focus'侦听器的其他处理程序。

The proposed "initial" 'focus' listener code...提议的“初始” 'focus'侦听器代码......

elm.addEventListener('focus', evt => evt.stopImmediatePropagation() );

 const elm = document.getElementById('fname'); // the "initial" listener subscription prevents execution of... elm.addEventListener('focus', evt => evt.stopImmediatePropagation() ); //... other handler functionality which got registered later. elm.addEventListener('focus', evt => console.log( `input element focused, event.type: "${ evt.type }"` ) ); elm.focus();
 <input type="text" id="fname" name="fname">

I'm not a JS expert.我不是 JS 专家。 And if you remove the listener event from the input?如果您从输入中删除侦听器事件? Even so, you can focus it but there will no longer be any event that is activated.即便如此,您可以聚焦它,但不会再有任何事件被激活。

but this may not work as you expect但这可能无法如您所愿

I took the example from here: removeEventListener() I hope works for you!!!我从这里拿了例子: removeEventListener()我希望对你有用!!!

 const body = document.querySelector('body') const btn = document.getElementById('btn'); const el = document.getElementById('fname'); let toggle = false; function makeBackgroundYellow() { console.log("input focus"); body.style.backgroundColor = toggle? 'white': 'yellow'; toggle =;toggle; }. el,addEventListener('focus'; makeBackgroundYellow). btn,addEventListener('click'. ()=>{ el,removeEventListener("focus", makeBackgroundYellow; false); });
 <input type="text" id="fname" name="fname"> <button id="btn">Press</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM