动态替换css文件(并将新样式应用于页面)

我有一个页面,<link>在标题中加载了名为的CSS light.css。我还有一个名为的文件dark.css。我想要一个按钮来交换页面的样式(css文件中有40个选择器,有些在两个文件中不匹配)。

如何删除对light.cssJS的引用并删除所有应用的样式,然后dark.css从中加载并应用所有样式?我不能简单地重置所有元素,因为一些样式是通过不同的css文件应用的,有些是由JS动态生成的。没有重新加载页面,有没有一种简单而有效的方法呢?香草JS是首选,但我会使用jQuery进行后续处理,所以jQ也没关系。


慕村225694
浏览 1370回答 4
4回答

qq_力学笃行_0

大佬你好,我想问下你之前做的react 后台管理系统 有demo地址或者 github地址吗我想参考下,不胜感激

Qyouu

您可以创建一个新链接,并用新链接替换旧链接。如果将它放在一个函数中,您可以在需要的地方重用它。Javascript:function changeCSS(cssFile, cssLinkIndex) {&nbsp; &nbsp; var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);&nbsp; &nbsp; var newlink = document.createElement("link");&nbsp; &nbsp; newlink.setAttribute("rel", "stylesheet");&nbsp; &nbsp; newlink.setAttribute("type", "text/css");&nbsp; &nbsp; newlink.setAttribute("href", cssFile);&nbsp; &nbsp; document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);}HTML:<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <title>Changing CSS</title>&nbsp; &nbsp; &nbsp; &nbsp; <link rel="stylesheet" type="text/css" href="positive.css"/>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <a href="#" onclick="changeCSS('positive.css', 0);">STYLE 1</a>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <a href="#" onclick="changeCSS('negative.css', 0);">STYLE 2</a>&nbsp; &nbsp; </body></html>为简单起见,我使用了内联javascript。在制作中,您可能希望使用不显眼的事件侦听器。

慕容708150

如果在link元素上设置ID<link rel="stylesheet" id="stylesheet" href="stylesheet1.css"/>你可以用Javascript来定位它document.getElementsByTagName('head')[0].getElementById('stylesheet').href='stylesheet2.css';要不就..document.getElementById('stylesheet').href='stylesheet2.css';这是一个更彻底的例子:<head>&nbsp; &nbsp; <script>&nbsp; &nbsp; function setStyleSheet(url){&nbsp; &nbsp; &nbsp; &nbsp;var stylesheet = document.getElementById("stylesheet");&nbsp; &nbsp; &nbsp; &nbsp;stylesheet.setAttribute('href', url);&nbsp; &nbsp; }&nbsp; &nbsp; </script>&nbsp; &nbsp; <link id="stylesheet" rel="stylesheet" type="text/css" href="stylesheet1.css"/></head><body>&nbsp; &nbsp; <a onclick="setStyleSheet('stylesheet1.css')" href="#">Style 1</a>&nbsp; &nbsp; <a onclick="setStyleSheet('stylesheet2.css')" href="#">Style 2</a></body>
打开App,查看更多内容
随时随地看视频慕课网APP