简体   繁体   English

使用媒体查询在调整大小窗口期间隐藏div

[英]Hide div during resize window using media queries

I want to create a responsive template to show a custom mobile menu. 我想创建一个响应模板来显示自定义移动菜单。 When i click on an image, i use javascript to show or hide a div where there is the mobile menu. 当我单击图像时,我使用JavaScript来显示或隐藏有移动菜单的div。 I use media queries to show this image only if the screen width is less than 768px. 仅当屏幕宽度小于768px时,我才使用媒体查询来显示此图像。

CSS Code CSS代码

#img_mobile{
    width: 15%;
    height: auto;   
    position: absolute;
    top: 10px;
    left: 0;
    display: none; //img is not visible for default..
}

@media only screen and (max-width: 768px){

    #img_mobile{
        display: block; //image is visible..
    }
}

Javascript Code: JavaScript代码:

<script type="text/javascript"> 
function hideOrShow(id){    
    if(document.getElementById(id).style.display != 'block'){
        //show..
        document.getElementById(id).style.display = 'block'
    }
    else{   
        //hide..
        document.getElementById(id).style.display = 'none'
    }   
}
</script>

//call the script on click image..
<a href="javascript:hideOrShow('menu_mobile');"><img alt="image" src="image.png"></a>

Everything works well, the image is shown only if the max-width is 768px or less and when i click on this image, my custom menu is shown or hidden. 一切正常,仅当最大宽度小于或等于768px时才显示该图像,并且当我单击此图像时,将显示或隐藏我的自定义菜单。 My problem is, when this menu is shown, if i resize my browser window and it become bigger than 768px, the image is hidden but the div with the menu is still visible, how can i avoid this? 我的问题是,当显示此菜单时,如果我调整浏览器窗口的大小并变得大于768px,则图像被隐藏,但带有菜单的div仍然可见,如何避免这种情况?

I try with this in CSS: 我尝试在CSS中使用:

@media only screen and (max-width: 1200px) {

    #menu_mobile{
        display: none; //try to set menu invisible, doesn't work anyway..
    }
}

//menu is set to display none for default..
#menu_mobile{
   display: none;
}

Hope i explained myself, thanks. 希望我自己解释一下,谢谢。

Just adding answer for future reference... 只是添加答案以供将来参考...

Wrap entire contents into a container that you want hidden/shown and reference that in the media query. 将全部内容包装到要隐藏/显示的容器中,并在媒体查询中引用它。

<div id="wrapper">
     <img src="something" />
     <ul id="menu"></ul>
</div>

As a simple example with markup then in the code you do exactly what you have but instead reference #wrapper instead of the img 作为一个带有标记的简单示例,然后在代码中完全执行您所拥有的,但是引用#wrapper而不是img

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

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