我有一个网站,我的<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>
标记放在文档的头部,因为它必须在主js脚本标记之后。
任何建议都是最受欢迎的。
保罗。
似乎没有任何理由将此代码视为无效。 <style>
元素是<noscript>
元素的有效子元素,并且都是<head>
或<body>
的有效子元素。
通常,您希望避免将标记与脚本和样式混合。我建议有一个应用你的样式的类,然后用JavaScript删除该类。通过这种方式,您可以将样式保存在一个位置,然后包含逻辑以删除这些样式以及脚本,完全避免嵌套的<noscript>
和<style>
方法。
<!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>
我同意@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>