Show and hide div with Window Size JavaScript?

余生颓废 提交于 2019-12-25 06:38:07

问题


I'm trying to show a div based on two or preferably three defined window sizes for mobile.

I'm currently trying to implement:

<script>

if( $(window).width() > 768 ) {
    $('#div1').show();
    $('$div2').hide();
} else {

}

if( $(window).width() < 768 ) {
    $('#div1').hide();
    $('$div2').show();
} else {

}

</script>

But it isn't working what am I doing wrong here?


回答1:


Your div2 selector is wrong. It should be a # not a $.

Also, you should consider using media queries for this!

#div2 {
  display: none;
}

@media screen and (max-width : 768px) {
  #div1 {
    display: none;
  }
  #div2 {
    display: block;
  }
}



回答2:


You need to do it inside the window.resize http://api.jquery.com/resize/ event

<script>
$(window).resize(function{
if( $(window).width() > 768 ) {
    $('#div1').show();
    $('#div2').hide();
} else {

}

if( $(window).width() < 768 ) {
    $('#div1').hide();
    $('#div2').show();
} else {

}
});
</script>

And yes the div2 should have # not $



来源:https://stackoverflow.com/questions/15801813/show-and-hide-div-with-window-size-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!