[英]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.