如何在css切换后刷新页面的样式
问题描述:
我有一个javascript函数,可以从影响我网站的两个不同的css文件切换。问题是css只是部分应用了我的功能,我需要刷新浏览器以获得整个新风格。
I have a javascript function that switch from two different css files that affect my web-site. The problem is that the css are only partially applied with my function and I need to refresh the browser to get the entire new style.
这是我的功能:
function switch_style ()
{
var head=document.getElementsByTagName('head')[0];
for (i = 0, link_tag = document.getElementsByTagName("link"); i < link_tag.length ; i++ )
{
if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) && link_tag[i].title)
{
if (link_tag[i].title == "normal")
{
head.removeChild(link_tag[i]);
}
}
}
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = '/templates/rhuk_milkyway/css/template_contrast.css';
head.appendChild(cssNode);
set_cookie( style_cookie_name, "contrast", style_cookie_duration );
}
如你所见,我删除然后在页眉中附加一个新样式。
As you can see i remove and then append a new style to the page header.
有没有办法刷新样式?
(它适用于所有浏览器)
(It happens with all browser)
答
我可能会忽略某些东西,但为什么只需在 html 或 body
元素?
I may be overlooking something, but why do you need to switch stylesheets when you can just add a new class to your html
or body
element?
优点:
- 切换速度更快。您不必等到新的css加载
- 替换样式可以包含在原始的
样式表中。 - 更简单。
jQuery.toggleClass
(或element.className
,如果你不使用jQuery)将完成所有工作。 - 无处不在。
- Faster switching. You do not have to wait until your new css is loaded - the alternate styles can be included in the original stylesheet.
- Simpler.
jQuery.toggleClass
(orelement.className
, if you do not use jQuery) will do all the job. - Works everywhere.
Con(s?):
- 您必须将新类添加到css中的所有选择器中。