我的页面上有几个链接(在 <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
调用之后)获取新的背景颜色:
var bgcolor = $('body').css('background-color');
alert(bgcolor);
问题是,我认为,浏览器需要一些时间来下载新的样式表,而且我有时会在警告消息中看到旧的背景颜色。有没有我可以绑定(bind)的事件,它只会在页面上加载所有样式表后才提醒我?
此刻,我能想到的就是使用 setTimeout(function(){}, 5000);
这不是很好,因为如果在页面上加载所有 CSS 需要更长/更短的时间怎么办。
如果我需要澄清任何事情,请告诉我,我可以提供更多代码。
最佳答案
您可以使用 AJAX 调用检索样式表的内容,然后将其插入内联样式 block ,而不是创建一个新的链接元素并将其附加到头部。这样,您就可以使用 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'));
});
});
我还没有实际测试过这段代码,所以可能会有一些语法错误,但逻辑应该足够健全。
关于javascript - 加载 CSS 后触发的 jQuery 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2571164/