且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何显示一个< div> if Javascript Enabled and a Different< div>如果不是?

更新时间:2022-05-31 06:09:06

尝试这样的。它优雅地降级,不需要< noscript /> 标记。

Try something like this. It degrades gracefully and doesn't require a <noscript /> tag.

<div id="hasJavaScript" style="display: none">
    <!-- Contents hidden when JavaScript is disabled -->
</div>

<div id="noscript">
    <!-- Contents shown only when JavaScript is disabled -->
</div>

<script type="text/javascript">

    document.getElementById('hasJavaScript').style.display = 'block';
    document.getElementById('noscript').style.display = 'none';

</script>

为了简化示例,我使用了ID。这将更适合使用类。此外,最体面的初学者框架,例如 HTML5 Boilerplate Modernizr 将使用HTML标签上的CSS类来实现这一点,因此您可以使用全局方式从CSS文件中隐藏/显示内容,而不是使用JS。 < html /> 标记以 no-js CSS类开头, c $ c> js 在JS中的类。这允许你只使用适当的类前缀任何依赖于JS的存在的任何CSS规则。这是更语义的,因为它将逻辑事物(不管页面是否正在运行JS)中的表示性东西(应该在视觉上隐藏/显示)分离。

To keep the example short, I used IDs. It would be more appropriate to use classes. Also, most decent starter frameworks such as HTML5 Boilerplate and Modernizr will do this using CSS classes on the HTML tag so you have a global way to hide/show content from your CSS file instead of using JS. The <html /> tag starts with a no-js CSS class and it gets replaced by a js class in JS. This allows you to just prefix any CSS rules that are dependent on the existence of JS with the appropriate class. This is more semantic since it separates presentational things (what should be visually hidden/shown) from logical things (whether the page is running JS or not).

另一个回答原始问题的选择是在头文件中添加默认的CSS文档的链接,并使用JavaScript删除它。 (免责声明)我没有测试过,但它也应该在所有浏览器上工作。

Another option for answering the original question is to add the link to the CSS document in the head by default and remove it using JavaScript. (DISCLAIMER) I haven't tested this, but it should also work across all browsers.

<script type="text/javascript">
    var cssDocs = document.getElementsByTagName('LINK');
    for (var i = 0; i < cssDocs.length; i++) {
        var css = cssDocs[i];
        if (css.href === 'css/hide-slideshow.css') {
            var parent = css.parentNode;
            parent.removeChild(css);
            break;
        }
    }
</script>

如果您使用 jQuery

$("link[href='css/hide-slideshow.css']").remove();