简体   繁体   English

浏览器调整大小时如何更改div样式

[英]How to change the div style when browser resize

I am creating a script where when a div is larger than normal because of a resize it change the style of the div. 我正在创建一个脚本,其中当div由于调整大小而比正常大时,它会更改div的样式。

I came up with this but for some reason sometimes it says the width is 0 and I can't really figure it out why. 我想出了这个,但由于某种原因,有时它说宽度为0,我无法弄清楚为什么。 Also when I change the amount of when the div has to change it doesn't work and it doesn't change back. 另外,当我更改div必须更改的数量时,它不起作用,并且也不会更改回去。

 window.addEventListener('resize', height); function height() { var height = document.getElementById('noline').offsetHeight; document.getElementById("noline").innerHTML = height; if (height <= 20) { document.getElementById('noline').setAttribute('id', 'line1'); } else { document.getElementById('line1').setAttribute('id', 'noline'); } } 
 #noline { border: solid 5px blue; } #line1 { border: solid 5px black; } 
 <div id="noline"> </div> 

I checked stackoverflow but couldn't really find a easy understandable answer and because I am new to javascript I am not really sure what I did wrong, so I was wondering what I did wrong, how to fix it and why does it happen. 我检查了stackoverflow,但是并没有真正找到一个容易理解的答案,因为我是javascript新手,所以我不确定自己做错了什么,所以我想知道自己做错了什么,如何解决它以及为什么会发生。

Thanks! 谢谢!

you can use @media rules in your css file. 您可以在css文件中使用@media规则。

@media (max-width: 720px) {
    .something{
         .
         .
         .
    }
}

A clean solution would be to use the css media queries. 一个干净的解决方案是使用CSS媒体查询。 You first want to know the dimension of browser you want to target. 您首先要知道要定位的浏览器的尺寸。 Then do something like this 然后做这样的事情

@media (max-width: 600px) {
  .div1 {

  }
}


 @media (max-width: 720px) {
      .div2 {

      }
    }

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

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