簡體   English   中英

如何更改頁面中所有元素的CSS-JavaScript

[英]How to change the CSS of all the elements in the page - JavaScript

我正在尋找使用JavaScript (運行時)更新樣式表的最佳方法。 到目前為止,我知道我可以使用querySelectorAll()做到這一點。 這使您所有與頁面上的查詢匹配的元素。 這種方法的問題在於,如果在DOM上安裝了新元素。 我將不得不手動替換其樣式,並且它變得更加混亂。

document.styleSheets可能是我正在尋找的解決方案,但是我似乎找不到一種簡單的方法來查找和替換CSS規則和/或屬性。 它幾乎沒有有用的功能,例如insertRuleaddRule 我不確定如何有效地使用它們來替換CSS屬性。

任何幫助,將不勝感激!

PS:雖然我更喜歡JavaScript ,但是jQuery也可以正常工作。 我可以找到一種將jQuery轉換為JavaScript

Background:我每天使用的網站很少,例如waffle.io ,我不喜歡它們的主題。 我正在嘗試使用Chrome ExtensionJavaScript對其進行自定義。 在這種情況下,更改HTML屬性將無濟於事,因為waffle.io不斷更新DOM。 我想在開始時運行一次script ,並且希望新安裝的元素具有更新的樣式。 由於DOM中的這種持續變化,我相信更新樣式表本身中的CSS規則/屬性非常重要。 (我可能是錯的)

如果尚不清楚我要達到的目標,請告訴我。

不能100%地確定要執行的操作,但是可以執行的操作是將html標簽引入一個類,該類充當要嘗試實現的替代。

因此,默認情況下,您將擁有:

<html class="normal">
...
</html>

並使用javascript,您只需替換/添加“ updated”類或任何其他內容:

<html class="normal updated">
...
</html>

然后,在樣式表中,您可以擁有:

.normal .foo { /* normal styles */ }
.normal.updated .foo { /* the other styles */ }

這樣一來, .updated將predecence了.normal.foo類,因為它會具有較高的特異性。 如果我正確理解了您的問題,這可能是使用JS和CSS定位頁面上所有元素的最簡單方法。

希望有幫助!

我認為您不清楚要做什么,但是您可以使用js輕松更改外部鏈接樣式表的src屬性

您可以做這種事情。 在這里,我正在更改所有元素的字體大小。 同樣,您可以使用其他屬性。

您可以在html元素上添加類,也可以僅在CSS中為html元素添加屬性。

 <!Doctype html> <html> <head> <style> html { font-size: 10px } * { font-size: 1rem } .first { font-size: 1.2rem } .second { font-size: 1.5rem } </style> <script> function increaseFontSize (key) { const fontSize = key === 'small' ? '10px' : '16px' document.documentElement.style.fontSize = fontSize } </script> </head> <body> <button onclick="increaseFontSize('large')">+</button> <button onclick="increaseFontSize('small')">-</button> <p class="first"> The constraints parameter is a MediaStreamConstraints object with two members: video and audio, describing the media types requested. Either or both must be specified. If the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with NotFoundError. </p> <p> The constraints parameter is a MediaStreamConstraints object with two members: video and audio, describing the media types requested. Either or both must be specified. If the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with NotFoundError. </p> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM