CSS:为没有javascript支持的浏览器隐藏元素

时间:2015-09-16 23:27:14

标签: html css modernizr

所以我使用Modernizr来检测javascript。基于.no-js类,我有以下内容:

html.no-js .navContainer {
    visibility: visible !important;
}
.navContainer{
    visibility: hidden;
}

如果用户启用了javascript,则隐藏该元素。如果他们没有启用javascript,则该元素可见。

效果很好。现在我想做相反的事情。也就是说,如果用户没有javascript,我想要一个隐藏元素。最好的方法是什么?

我尝试过很多东西,包括很多变化:

html.no-js .navButton {
    display: none;
}

html .navButton {
    display: block;
}

但到目前为止,没有任何效果。我的理解是,html.no-js .navButton只应在<html class="no-js">上进行选择。那不是这样吗?

2 个答案:

答案 0 :(得分:4)

尝试将其直接放入页面中,如下所示。

<noscript>
 <style type="text/css">
 @import url (nojs.css);

 .navButton {
     display: none;
 }

 </style>
 </noscript>

答案 1 :(得分:0)

要以可视方式隐藏屏幕阅读器并使用

html.no-js .navbutton {
  display: none
}

如果您想要通过视觉和屏幕阅读器隐藏,但保持布局:

html.no-js .navbutton {
  visibility: hidden;
}

仅在视觉上隐藏,但可供屏幕阅读器使用:

html.no-js .navbutton {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

扩展前一个样式,以便在通过键盘导航到该元素时可以聚焦:

html.no-js .navbutton.focusable:active,
html.no-js .navbutton.focusable:focus {
  clip: auto;
  height: auto;
  margin: 0;
  overflow: visible;
  position: static;
  width: auto;
}

来源