代码之家  ›  专栏  ›  技术社区  ›  pjk_ok

如何在<noscript>标记中使用<style>元素?

  •  0
  • pjk_ok  · 技术社区  · 6 年前

    我有一个网站 <noscript> 我下面的标签 <script> 标记以防javascript加载失败。它基本上关闭了一些css值来处理一些平滑的滚动js代码和一个预加载程序。

    但是,当我通过w3c html验证器运行该站点时,它会说:

    Element style not allowed as child of element noscript in this context. (Suppressing further errors from this subtree.)

    我使用的代码是:

    <noscript>
    <style type="text/css" media="screen">#main-body {opacity: 1 !important; } .viewport {position: static; overflow: visible;} h1, h2, h3 {opacity: 1} .st-ca-title, .st-ca-sub, .st-co-title, .st-co-sub, .js-client-stagger, .btn, .btn a, .st-ho-title, .st-ho-sub, .st-ho-p {opacity: 1}
    </style>
    </noscript>
    

    这段代码做了我想做的事情(即,如果js加载失败,确保站点仍然正常工作),但是我是否做了一些错误的事情来得到这个错误?

    我不能把 <NoScript & GT; 标记在文档头部,因为它必须位于主js脚本标记之后。

    任何建议都是非常欢迎的。

    保罗。

    0 回复  |  直到 6 年前
        1
  •  1
  •   jaasum    6 年前

    似乎没有任何理由将此代码视为无效。一 <style> 元素是 <noscript> 元素和两者都是 <head> <body> .

    尽管您通常希望避免将标记与脚本和样式混合在一起。我建议使用一个应用样式的类,然后使用javascript删除该类。这样,您可以将样式保存在一个地方,然后将逻辑与脚本一起删除这些样式,以避免嵌套 <NoScript & GT; <风格& GT; 完全接近。

    <!DOCTYPE html>
    <html>
      <head>
        <style>
          .no-js {
            /* "no script" styles here */
          }
        </style>
      </head>
      <body class="no-js">
        <script>
          document.querySelector('body').classList.remove('no-js');
        </script>
      </body>
    </html>
    
        2
  •  0
  •   David Bray    6 年前

    我同意“jaasum”的说法,不要这样混合

    不管它不会有你正在寻找的限制性影响,范围css像这样..这里红色应用于noscript标记内部,否则应用绿色。

    <!DOCTYPE html>
    <html>
        <head>
            <style>
                .danger {
                    color: green; font-weight: bold;
                }
    
                noscript .danger {
                    color: red; font-weight: bold;
                }
            </style>
    
            <script>
                function myStuff() {
                    let p = document.createElement('p');
                    p.innerHTML = '<p>you seem to have <span class="danger">scripts enabled...</span></p>';
                    document.body.appendChild( p);
    
                }
    
            </script>
    
        </head>
    
        <body onload="myStuff()">
            <noscript>
                <h1>Script</h1>
    
                <p>you need <span class="danger">scripts enabled</span></p>
    
            </noscript>
    
        </body>
    
    </html>