响应式设计和点击事件

Jab*_*key 1 javascript css inline-styles media-queries responsive-design

我有一个移动菜单按钮(只能通过 display:block 使用媒体查询查看)。单击该按钮时,会出现我的主“移动”菜单 - 我使用简单的 javascript 代码(见下文)执行此操作。

问题...如果我单击按钮展开菜单(将内联样式从 display:none 更改为 display:block),然后增加浏览器大小...我的菜单不再消失。因此,内联样式无法识别媒体查询...

下面是扩展我的菜单的脚本......

<!-- Menu Expander / Toggle Visibility -->
<script type="text/javascript">
function toggle_menu(id) {
    var e = document.getElementById(id);
    if (e.style.display == 'block') e.style.display = 'none';
    else e.style.display = 'block';
}
</script>
Run Code Online (Sandbox Code Playgroud)

以下是一些样式.... 您将看到 menu-mobile(即实际菜单)和 mobile-menu-but(即按钮)被隐藏(显示:无)。当浏览器窗口缩小时,按钮出现(在媒体查询中带有 display:block),但菜单仍然隐藏。然后,当您单击 javascript 按钮时,会添加内联样式 display:block 以设置移动菜单。

#mobile-menu-but, #menu-mobile { display:none; } 
#menu a, #menu a:link { padding: 15px 16px 12px 16px; }

@media (max-width: 790px) { 
  /* Switch to Mobile Menu when too long */
  #menu { display:none; } /* Hide Main Menu  */
  #mobile-menu-but { display:block; float:right; margin:0 20px 0 0; height:50px; padding:5px 0; } 
   #mobile-menu-but a { float:right; }
    .menu-txt { margin:10px 10px 0 0; float:right; }

    #menu-mobile { width:100%; background-color:#000; text-transform:uppercase; 
            font-size:16px; font-family:"AvantGarde", "Helvetica Neue", Arial, Helvetica, sans-serif; } }
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

您可以添加和删除类值来更改元素外观,而不是直接操作元素样式。类的规则可能会受到媒体查询的影响,因为它们会直接进入样式表。

现代浏览器提供.classListAPI:

function toggle_menu(id) {
    var e = document.getElementById(id);
    if (e.classList.contains("showing"))
      e.classList.remove("showing");
    else
      e.classList.add("showing");
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的 CSS 中,您可以拥有:

  #menu { display: none; }
  #menu.showing { display: block; }
Run Code Online (Sandbox Code Playgroud)

如果您只想在屏幕大时显示菜单,请在上面这些行之后添加以下内容:

  @media screen and (max-width: 700px) { /* or whatever size you want */
    #menu.showing { display: none; }
  }
Run Code Online (Sandbox Code Playgroud)

(还有其他策略可用于在媒体查询中安排规则,具体取决于您要执行的操作。