简体   繁体   English

使用 addEventListener 更改 DIV 的 CSS

[英]Change CSS of DIV with addEventListener

I have this HTML我有这个 HTML

<div class="content" id="content2">text<br></div>

and want to, for example, change CSS or just show Alert.并且想要,例如,更改 CSS 或仅显示 Alert。

var chan = document.getElementById("content2");

if(chan){
  chan.addEventListener('click', function swapper() {
   alert('Ready!');
   //document.getElementById('content').style.display = "none";
})};

Why doesn't work?为什么不起作用? What I need to read?我需要阅读什么?

I would prefer using some code like this to change the css styles at (eg) click-event:我更喜欢使用这样的一些代码来更改(例如)click-event 的 css 样式:

 function addEventListener() { var element = document.getElementById("content2"); element.addEventListener('click', function swapper() { element.style.color = "red" // change the text color element.style.background = "black" // change the background color element.style.fontSize = "20px" // change the background color }) } window.onload = function() { addEventListener() }
 <div class="content" id="content2">click this text<br></div>

Edit: Keep in mind to use some unload-trigger (event) like window.onload to avoid issues:编辑:请记住使用一些卸载触发器(事件),如window.onload以避免出现问题:

window.onload = function() {

  // code to add event listeners, etc.

}

You should wrap your code in window.onload to make sure the DOM has loaded first before you attempt to manipulate it's elements.您应该将代码包装在window.onload 中,以确保在尝试操作其元素之前已先加载 DOM。

 window.onload = function() { var chan = document.getElementById('content2') chan.addEventListener('click', function swapper() { alert('Ready!') }) }
 <div id="content2">Click me</div>

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

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