用程序从单个HTML元素中删除CSS样式规则

Remove CSS style rules from a single HTML element programatically

本文关键字:删除 CSS 样式 规则 元素 程序 单个 HTML      更新时间:2023-12-26

我想在文档中添加一些根本没有样式的HTML元素。但我需要保证,无论项目、网页还是其他任何东西,这些元素看起来都不会有什么不同。这些元素将通过Javascript插入到页面中,并且将是SPAN。

我的想法是将SPAN添加到文档中的样式文本片段中。但是之前可能已经在SPAN元素中添加了一些样式,这将改变我预期的结果。

所以,假设我正在编写一个Widget,你们中的任何人都可以在自己的网页中使用它。这就是为什么我不能直接更改元素的样式,比如直接更改样式表。该解决方案必须通过Javascript实现。不需要JQuery。

<head>
   <style>
     span{
       font-weight: bold;
       /*anything else goes below*/
     }
   </style>
</head>
<body>
   <span class='a_regular_span'>This text must be bold and anything else</span>
   <span>This text must have only the CSS rules I applied by Javascript, and must not inherit the rules for all SPANs in the page</span>
</body>

有什么想法吗?

假设我正在编写一个Widget,而你们中的任何人都可能在使用它在您自己的网页中。这就是为什么我不能做太多改变元素风格直接

可以使用具有scoped属性的style元素。通过这种方式,您可以只设置元素的样式,而不会影响页面的其他部分。

但要注意,旧的浏览器不支持它

如果您不希望页面的样式影响您的元素,请参阅如何防止CSS影响某些元素?

如果您真的希望将元素的样式与页面上其他元素的样式分开,可以使用自定义标记来实现这一点。

例如,您可以使用customspan,而不是使用span,并以任何您喜欢的方式设置这些元素的样式。

<head>
   <style>
     span{
       font-weight: bold;
       /*anything else goes below*/
     }
   </style>
</head>
<body>
   <span class='a_regular_span'>This text must be bold and anything else</span>
   <customspan>This text must have only the CSS rules I applied by Javascript, and must not inherit the rules for all SPANs in the page</customspan>
</body>

你能试试这个吗?

 <style>
      span{
        font-weight: bold;
        /*anything else goes below*/
      }    .a_regular_span span{ font-weight: normal;
        /*anything else goes below*/
     }
 </style>