【发布时间】:2014-10-03 13:46:17
【问题描述】:
我想创建一个响应式模板来显示自定义移动菜单。当我单击图像时,我使用 javascript 显示或隐藏有移动菜单的 div。仅当屏幕宽度小于 768 像素时,我才会使用媒体查询来显示此图像。
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 代码:
<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>
一切正常,仅当最大宽度为 768 像素或更少时才会显示图像,并且当我单击此图像时,会显示或隐藏我的自定义菜单。 我的问题是,当显示这个菜单时,如果我调整浏览器窗口的大小并且它变得大于 768px,图像被隐藏但带有菜单的 div 仍然可见,我该如何避免这种情况?
我在 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;
}
希望我自己解释一下,谢谢。
【问题讨论】:
-
你能把所有东西都包装在一个容器中,然后用它作为显示/隐藏元素吗?这样,如果你隐藏容器,里面的所有东西也会消失
-
谢谢,这很容易,但我是网络开发的新手。我刚刚为菜单创建了一个新容器并将其设置为 display: none 默认和 display: block if max-width = 768px;因此,如果容器为空且未显示菜单,则不会占用空间,否则会显示菜单。如果最大宽度 > 768px,则无法显示菜单,因为容器未显示。谢谢!
标签: javascript html css media-queries