Dav*_*ave 24 javascript css jquery events javascript-events
我的页面上有几个链接(在a中<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;
});
Run Code Online (Sandbox Code Playgroud)
现在,在我更改了页面上的样式后,我希望使用以下代码(我在$('head').append调用后放置)获取新的背景颜色:
var bgcolor = $('body').css('background-color');
alert(bgcolor);
Run Code Online (Sandbox Code Playgroud)
问题是,我认为浏览器下载新样式表需要一些时间,我有时会在警报消息中获得旧的背景颜色.是否有一些我可以绑定的事件只会在页面上加载所有样式表后提醒我?
目前,我所能想到的只是使用setTimeout(function(){}, 5000);不太好的,因为如果在页面上加载所有CSS需要更长/更短的时间.
如果我需要澄清任何内容,请告诉我,我可以提供更多代码.
Ben*_*ull 19
您可以使用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'));
});
});
Run Code Online (Sandbox Code Playgroud)
我实际上没有测试过这段代码,因此可能存在一些语法错误,但逻辑应该足够健全.
Mic*_*ael 12
可以监视与url关联的任何元素的load事件,这在加载css样式表时不适合你吗?http://api.jquery.com/load-event/
尝试这样的事情:
var path = $(this).attr('href');
$('head link').remove();
var styleSheet = $('<link type="text/css" href="'+path+'" rel="stylesheet" />');
styleSheet.load(function(){alert("Loaded");});
$('head').append(styleSheet);
Run Code Online (Sandbox Code Playgroud)
编辑:正如下面指出这只适用于IE,谁会想到?
| 归档时间: |
|
| 查看次数: |
22349 次 |
| 最近记录: |