如何禁用HTML / JS中的STYLE元素?

lev*_*evi 3 html javascript css

我们有一个样式节点,我们想在HTML文档中编写,但是我们不想对其进行处理……只是为了进一步使用,我们之所以不使用隐藏节点,是因为我们想要在Dev时保留语法突出显示。

在Javascript中,可以通过更改type属性来完成

例如:

<script type="gzip/text"></script>
Run Code Online (Sandbox Code Playgroud)

会导致脚本无法执行...

有可能在style节点上做同样的事情吗?

col*_*lxi 5

您可以使用启用/禁用样式元素media attribute

通过将其设置为与任何设备都不匹配的值,实际上是在禁用它。

<style media="max-width: 1px">
   /* Nothing contained in this styles element will be applied */
</style>
Run Code Online (Sandbox Code Playgroud)

通过动态设置和删除此属性及其值,可以模拟启用/禁用的行为,如以下示例所示:

<style media="max-width: 1px">
   /* Nothing contained in this styles element will be applied */
</style>
Run Code Online (Sandbox Code Playgroud)
document.getElementById('but').addEventListener('click', function toggle(){
  let styleEl = document.getElementById('styles')
  // toggle enabled/disabled
  if(styleEl.hasAttribute('media')) styleEl.removeAttribute('media')
  else styleEl.setAttribute('media', "max-width: 1px")
})
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用查询`media =“ not all”`评估为false,并且也禁用该块。它可能更具语义和直观性,但是我不确定跨浏览器是否安全。 (2认同)

Ale*_*oma 5

您也可以通过将类型更改为文本来禁用它。

这是一个例子

function toggle(item){
   if (typeof item  === "string")// its an id 
     item = document.getElementById(item);
   if (item.getAttribute("type") == "text")
       item.removeAttribute("type");
   else item.setAttribute("type", "text"); // this will disable it 
}
Run Code Online (Sandbox Code Playgroud)
<style id="styleOne">
.active{
color:red;
}
</style>


<p onclick="toggle('styleOne')" class="active">Toggle Style</p>
Run Code Online (Sandbox Code Playgroud)