简体   繁体   English

JavaScript:如何在删除“调整大小”事件后添加一个类?

[英]JavaScript: How do I add a class on a 'resize' event after removing it?

I am adding an event listener to the window to listen for the resize event. 我在窗口中添加了一个事件监听器,以监听resize事件。 Essentially I'd like to remove the 'center' class when the width of the browser falls below 768px and then add it back when we are above 768px. 本质上,当浏览器的宽度低于768px时,我想删除'center'类,然后当高于768px时,将其添加回去。

 window.addEventListener('resize', function() {
    var width = 0,
        doc = document,
        div = doc.getElementsByTagName('div'), i;
    if (window.innerHeight) {
        width = window.innerWidth;
    } else if (doc.documentElement && doc.document.documentElement.clientHeight) {
        width = doc.documentElement.clientWidth;
    } else if (doc.body) {
        width = doc.body.clientWidth;
    }
    if (width < 768) {
        for (i = 0; i < div.length; i++) {
            div[i].classList.remove('center');
        }
    } else {
        div[i].classList.add('center');
    }
}, false);

It removes it correctly but upon checking the console, I immediately get this error. 它可以正确删除它,但是在检查控制台后,我立即收到此错误。 Not sure why it would log that error from the onset... 不知道为什么会从一开始就记录该错误...

index.html:591 Uncaught TypeError: Cannot read property 'classList' of undefined(…)

Appreciate any help! 感谢任何帮助!

You don't need js, css only: 您不需要js,仅需要CSS:

 .media { background-color: blue; } @media (max-width: 600px) { .media { background-color: red; } } 
 <div class="media"> Hello world</div> 

codepen 码笔

read here about media queries 在这里阅读有关媒体查询的信息

You've messed up your loop with your if statement. 您已经用if语句弄乱了循环。

   if (width < 768) {
     for (i = 0; i < div.length; i++) {
         div[i].classList.remove("center");
     }
   } else {
       div[i].classList.add("center");
   }

should be: 应该:

for (i = 0; i < div.length; i++) {
  if(width < 768)
       div[i].classList.remove("center");
   } else {
       div[i].classList.add("center");
   }
}

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

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