如何应用使用 jQuery 动态加载的内联和/或外部 CSS [英] How to apply inline and/or external CSS loaded dynamically with jQuery

查看:37
本文介绍了如何应用使用 jQuery 动态加载的内联和/或外部 CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Ajax 控件,它使用 jQuery 加载到 Yahoo 弹出窗口中.

I have an Ajax control that is loaded into a Yahoo popup using jQuery.

我只是使用一个简单的 .get 请求来加载 HTML.

I just use a simple .get request to load the HTML.

  $.get(contentUrl, null, function(response) {
         $('#dialog').find('.bd').assertOne().html(response);
     }, "waitDlg");

现在的问题是加载的内容需要它自己的 CSS,它实际上是动态创建的.我可以选择内联或使用外部 CSS 样式表.

Now the problem is that the content that is loaded needs its own CSS which is actually dynamically created. I have a choice of either inlining the or using an external CSS stylesheet.

Chrome 中的测试表明,通过 AJAX 加载的 CSS 在使用上述代码添加到 DOM 时并未评估/应用.

Testing in Chrome shows that the CSS loaded via AJAX is not evaluated/applied at the time it is added to the DOM using the above code.

Internet Explorer 评估内联 CSS,当它卡在 DOM 中时,Chrome 不会.由于完全不相关的问题,我目前无法在 FireFox 中进行测试.

Internet Explorer will evaluate an inlined CSS when it just gets stuck in the DOM but Chrome will not. I am currently unable to test in FireFox because of a completely unrelated issue.

jQuery 中是否有任何方法可以评估动态添加到 DOM 的样式表作为内联还是 ?

Is there any way in jQuery to evaluate a stylesheet that was dynamically added to the DOM as either an inline or ?

我想这样做的原因有很多:

There are many reasons I'd like to do this:

  • 弹出窗口中的 CSS 属于弹出窗口,可能完全来自不同的环境
  • 它是动态的,除非万不得已,否则我不想将它放在父页面中
  • 我计划让它像这样工作,但它没有!:-(

推荐答案

给定样式表的路径(或将生成有效 CSS 的某些 URL):

Given a path to your stylesheet (or some URL that will generate valid CSS):

var myStylesLocation = "myStyles.css";

...其中之一应该可以工作:

...either one of these should work:

$.get(myStylesLocation, function(css)
{
   $('<style type="text/css"></style>')
      .html(css)
      .appendTo("head");
});   

使用动态创建的

加载

$('<link rel="stylesheet" type="text/css" href="'+myStylesLocation+'" >')
   .appendTo("head");

使用动态创建的 <style>

加载

$('<style type="text/css"></style>')
    .html('@import url("' + myStylesLocation + '")')
    .appendTo("head");

$('<style type="text/css">@import url("' + myStylesLocation + '")</style>')
    .appendTo("head");

这篇关于如何应用使用 jQuery 动态加载的内联和/或外部 CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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