CSS/Javascript-是否"display:none"暂时删除任何关联的事件侦听器? [英] CSS / Javascript - Does "display:none" remove any associated event listeners temporarily?

查看:117
本文介绍了CSS/Javascript-是否"display:none"暂时删除任何关联的事件侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在效率方面的思考更多.如果我选择将元素的显示设置为none,则javascript将继续侦听附加到该事件的事件,还是暂时删除它们直到显示恢复?

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?

推荐答案

这取决于发生的事件的类型.让我们尝试使用click事件:

It depends on the kind of events happening. Let's try using a click event:

$(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>

测试用例

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

结论

无论是否在屏幕上或屏幕外看到DOM元素,所有事件和行为都将保留.仅CSS显示被更改.没什么,与行为有关的任何东西都不会受到影响.

Whether or not, the DOM element is visible in the screen or off-screen, all the events and behaviours are preserved. Only the CSS display is changed. 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.

因此,这表明在存在visibility: hiddendisplay: none时会保留事件.

So this shows that the events are preserved when there's visibility: hidden or display: none.

这篇关于CSS/Javascript-是否"display:none"暂时删除任何关联的事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆