我的页面上有几个链接(在<div id="theme-selector">
) 允许您更改 CSS 样式表:
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$('head link').remove();
$('head').append('<link type="text/css" href="'+path+'" rel="stylesheet" />');
return false;
});
现在,在更改页面上的样式后,我想使用以下代码(我将其放在$('head').append
call):
var bgcolor = $('body').css('background-color');
alert(bgcolor);
我认为问题是浏览器需要一些时间来下载新的样式表,并且有时我会在警报消息中看到旧的背景颜色。是否有一些我可以绑定的事件,只有在页面上加载所有样式表后才会提醒我?
目前,我能想到的就是使用setTimeout(function(){}, 5000);
这不太好,因为如果加载页面上的所有 CSS 需要更长/更短的时间怎么办?
如果我需要澄清任何事情,请告诉我,我可以提供更多代码。
您可以使用 AJAX 调用检索样式表的内容,并将其插入内联样式块中,而不是创建新的链接元素并将其附加到头部。这样,您就可以使用 jQuery 的“完整”回调来触发您的检查。
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$.get(path, function(response){
//Check if the user theme element is in place - if not, create it.
if (!$('#userTheme').length) $('head').append('<style id="userTheme"></style>');
//populate the theme element with the new style (replace the old one if necessary)
$('#userTheme').text(response);
//Check whatever you want about the new style:
alert($('body').css('background-color'));
});
});
我还没有实际测试过这段代码,因此可能存在一些语法错误,但逻辑应该足够健全。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)