简体   繁体   English

CSS / Javascript - “display:none”暂时删除任何关联的事件监听器吗?

[英]CSS / Javascript - Does “display:none” remove any associated event listeners temporarily?

I'm thinking more in terms of efficiency. 我在效率方面的思考更多。 If I choose to set the display of an element to none , will javascript continue to listen for events attached to it, or does it temporarily remove them until the display is reverted back? 如果我选择将元素的显示设置为none ,javascript会继续侦听附加到它的事件,还是会暂时删除它们直到显示还原为止?

It depends on the kind of events happening. 这取决于发生的事件的类型。 Let's try using a click event: 让我们尝试使用click事件:

 $(function () { // Let's attach an event. $("#eventContainer").click(function () { $("#eventAffected").html("I changed."); }); // This will hide the container surely when you click. $("#hide-container").click(function () { $("#eventContainer").hide().css("display", "none"); }); // This will trigger the event on the element. $("#trigger-event").click(function () { $("#eventContainer").trigger("click"); }); }); 
 * {font-family: 'Segoe UI'; margin: 5px;} #eventContainer, #eventAffected {background-color: #ccf; text-align: center; padding: 5px;} #eventAffected {background-color: #cfc;} 
 <script src="https://code.jquery.com/jquery-1.9.1.js"></script> <div id="eventContainer">Hello I am the Event Box</div> <div id="eventAffected">Hello, I change when event triggered on the above.</div> <button id="hide-container">Hide</button> <button id="trigger-event">Trigger Click</button> 

Test Cases 测试用例

  1. Click on the First Div. 点击First Div。 Second Div Changes, event is triggered. 第二个Div更改,事件被触发。
  2. Click on the Trigger Click. 单击Trigger Click。 Second Div Changes, event is triggered. 第二个Div更改,事件被触发。
  3. Click on the Hide and Trigger Click. 单击隐藏和触发单击。 Second Div Changes, event is triggered. 第二个Div更改,事件被触发。

Conclusion 结论

Whether or not, the DOM element is visible in the screen or off-screen, all the events and behaviours are preserved. 无论是否在屏幕上或屏幕外显示DOM元素,都会保留所有事件和行为。 Only the CSS display is changed. 仅更改CSS显示。 Nothing else, nothing related to behaviour is affected. 没有别的,与行为无关的任何事情都会受到影响。

This is similar to all the events, only thing is, you cannot calculate the dimensions or box model. 这类似于所有事件,唯一的事情是,你无法计算尺寸或箱子模型。

So this shows that the events are preserved when there's visibility: hidden or display: none . 因此,这表明当visibility: hidden时会保留事件visibility: hiddendisplay: none

不,它不会删除它们,但由于元素及其所有后代都没有呈现,因此用户无法在其中任何一个上触发事件,因此浏览器永远不会测试该元素以查看是否它有任何事件处理程序。

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

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