加载 CSS 后触发的 jQuery 事件? [英] jQuery event that triggers after CSS is loaded?

查看:27
本文介绍了加载 CSS 后触发的 jQuery 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有几个链接(在 <div id="theme-selector"> 内)允许您更改 CSS 样式表:

I have a couple of links on my page (inside a <div id="theme-selector">) which allow you to change the CSS stylesheets:

$('#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 之后)获取新的背景颜色调用):

Now, after I've changed the style on the page, I want to get the new background color, using the following code (which I put after the $('head').append call):

var bgcolor = $('body').css('background-color');
alert(bgcolor); 

我认为问题是浏览器下载新样式表需要一些时间,有时我的警报消息中会出现旧的背景颜色.是否有一些我可以绑定的事件只会在页面上加载所有样式表后才会提醒我?

The problem is, I think, that it takes some time for the browser to download the new stylesheet and I sometimes get the old background color in my alert message. Is there some event I can bind that will only alert me after all the stylesheets are loaded on the page?

目前,我能想到的就是使用 setTimeout(function(){}, 5000); 这不是很好,因为如果需要更长/更短的时间来加载所有页面上的 CSS.

At the moment, all I can think of is using a setTimeout(function(){}, 5000); which isn't great, because what if it takes longer/shorter to load all the CSS on the page.

如果我需要澄清任何事情,请告诉我,我可以提供更多代码.

Let me know if I need to clarify anything and I can provide more code.

推荐答案

您可以使用 AJAX 调用检索样式表的内容,并将其插入内联元素,而不是创建新的链接元素并将其附加到头部样式块.这样,您就可以使用 jQuery 的完成"回调来触发您的支票.

Rather than creating a new link element and appending it to the head, you could retrieve the contents of the stylesheet with an AJAX call, and insert it into an inline style block. That way, you can use jQuery's 'complete' callback to fire off your check.

$('#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'));
  });
});

我还没有真正测试过这段代码,所以可能会有一些语法错误,但逻辑应该足够了.

I haven't actually tested this code, so there may be some syntax-y errors, but the logic should be sound enough.

这篇关于加载 CSS 后触发的 jQuery 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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