【问题标题】:How to link external stylesheet only if javascript is enabled仅在启用 javascript 时如何链接外部样式表
【发布时间】:2012-06-25 21:51:46
【问题描述】:

我有一个页面,我希望根据是否启用 javascript 设置不同的样式。

代码:

<link rel="stylesheet" href="./css/main.css" type="text/css" />

<noscript>
    <link rel="stylesheet" href="./css/noscript.css" type="text/css" />
</noscript>

我的问题是 noscript.css 只覆盖了一些属性,而不是全部。因此,由于 main.css 中包含更多样式,因此它也适用。只有被覆盖的样式看起来不错。如果我删除指向 main.css 的链接,页面看起来就像我想要的那样。

有没有办法将所有以前的样式“重置”为默认样式,或者在 noscript 上禁用指向 main.css 的链接?

谢谢!

【问题讨论】:

    标签: javascript html css noscript


    【解决方案1】:

    你可以这样做:

    <script>
      document.write('<link rel="stylesheet" href="./css/main.css" type="text/css" />');
    </script>
    <noscript>
        <link rel="stylesheet" href="./css/noscript.css" type="text/css" />
    </noscript>
    

    我通常不是document.write() 的忠实粉丝,但这是最简单的事情的一个例子。您当然可以创建 &lt;link&gt; 标签并将其附加到 &lt;head&gt; 或其他任何内容,如果它太令人反感的话。

    【讨论】:

      【解决方案2】:

      如果有人遇到这个老问题,我发现的最好方法(不需要 JS)是:

      <noscript>
      <!--
      </noscript>
      <link rel="stylesheet" href="./css/main.css" type="text/css" />
      <noscript>
      -->
      </noscript>
      

      所以如果你有JS,浏览器就会看到

      <link rel="stylesheet" href="./css/main.css" type="text/css" />
      

      没有JS,浏览器会看到

      <!--
      <link rel="stylesheet" href="./css/main.css" type="text/css" />
      -->
      

      【讨论】:

        【解决方案3】:
        var css = document.createElement('link');
        css.rel = 'stylesheet';
        css.type = 'etxt/css';
        css.href = './css/main.css';
        document.head.appendChild(css);
        

        【讨论】:

          猜你喜欢
          • 2013-12-08
          • 2016-01-02
          • 2017-04-05
          • 1970-01-01
          • 2019-07-18
          • 1970-01-01
          • 2011-07-19
          • 2014-06-06
          • 1970-01-01
          相关资源
          最近更新 更多