立即替换css文件(并将新样式应用于页面) [英] Replacing css file on the fly (and apply the new style to the page)

查看:147
本文介绍了立即替换css文件(并将新样式应用于页面)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a page which has <link> in the header that loads the CSS named light.css. I also have a file named dark.css. I want a button to swap the style of the page all together (there are 40 selectors used in css file and some do not match in two files).

我如何删除对 light.css 的引用,并删除所有应用的样式,然后加载 dark.css 并应用所有的样式从那?我不能简单地重置所有的元素,因为一些样式是通过不同的css文件应用,一些是由JS动态生成的。有没有一个简单,但有效的方式来做,而不重新加载页面? Vanilla JS是最好的,但是我将使用jQuery以后的处理,所以jQ也很好。

How can I remove reference to light.css with JS and remove all the styles that were applied and then load dark.css and apply all the styles from that? I can't simply reset all of the elements, since some of the styles are applied through different css files and some are dynamically generated by JS. Is there a simple, yet effective way to do that without reloading the page? Vanilla JS is preferable, however I will use jQuery for later processing anyways, so jQ is also fine.

推荐答案

=http://www.omnimint.com/A6/JavaScript/Change-external-CSS-stylesheet-file-with-JavaScript.html> Omnimint :

From Omnimint:

JavaScript:

The Javascript:

function changeCSS(cssFile, cssLinkIndex) {

    var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

    var newlink = document.createElement("link");
    newlink.setAttribute("rel", "stylesheet");
    newlink.setAttribute("type", "text/css");
    newlink.setAttribute("href", cssFile);

    document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}

HTML:

<html>
    <head>
        <title>Changing CSS</title>
        <link rel="stylesheet" type="text/css" href="positive.css"/>
    </head>
    <body>
        <a href="#" onclick="changeCSS('positive.css', 0);">STYLE 1</a> 
        <a href="#" onclick="changeCSS('negative.css', 0);">STYLE 2</a>
    </body>
</html>

为了简单起见,我使用了内联javascript。在生产中,您将使用不显眼的事件侦听器。

For simplicity, I used inline javascript. In production you would want to use unobtrusive event listeners.

这篇关于立即替换css文件(并将新样式应用于页面)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆