[英]Remove CSS style rules from a single HTML element programatically
我想在文档中添加一些根本没有样式的HTML元素。 但我需要确保,无论项目,网页或其他任何内容,这些元素的外观都不会有所不同。 这些元素将通过Javascript插入页面中,并将为SPAN。
我的想法是将SPAN添加到文档中的文本样式片段中。 但是以前可能已将某些样式添加到SPAN元素,这将改变我期望的结果。
因此,假设我正在编写一个小部件,并且您中的任何人都可以在自己的网页中使用它。 这就是为什么我不能做很多事情来直接更改元素的样式,例如直接更改样式表。 该解决方案必须通过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>
有任何想法吗?
因此,假设我正在编写一个小部件,并且您中的任何人都可以在自己的网页中使用它。 这就是为什么我不能做很多事情来直接更改元素的样式
您可以使用具有scoped
属性的style
元素。 这样,您可以仅设置元素的样式,而不会影响页面的其他部分。
但是请注意,旧的浏览器不支持它。
如果您不希望页面的样式影响元素,请参阅如何防止CSS影响某些元素?
如果您确实希望将元素的样式与页面上其他元素的样式分开,则可以使用自定义标记来执行此操作。
例如,您可以使用custompan并按自己喜欢的方式对这些元素进行样式设置,而不是使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.