繁体   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