使用jQuery向文档添加样式表

dsekswqp  于 2022-12-22  发布在  jQuery
关注(0)|答案(2)|浏览(169)
jQuery(document).ready(function($) { 
        /******* Load CSS *******/
        $('head').append('<link rel="stylesheet" type="text/css" media="all" href="'+('https:' == document.location.protocol ? 'https://' : 'http://') +'thesite.com/api/widgets/tghd/pages.css">');    
    });

上面的代码是我用来向文档添加样式表的代码。代码检查器显示代码已经添加,但是控制台没有显示浏览器已经请求了文档,样式没有生效。
如何将样式表添加到已加载的文档中并使其生效。
顺便说一句,如果有关系的话,我正在使用这个代码的小部件,所以我将跨多个域使用。
提前感谢您的任何帮助!

46scxncf

46scxncf1#

试试这个:

(function () {
    var li = document.createElement('link');
    li.type = 'text/css';     
    var href='http://' + 'thesite.com/api/widgets/tghd/pages.css';
    li.setAttribute('href', href);
    var s = document.getElementsByTagName('head')[0];
    s.appendChild(li, s);
})();
a7qyws3x

a7qyws3x2#

OK在做了几个测试之后,我终于弄清楚了到底是怎么回事。这个原始代码是由以下提供的:@维姬·贡萨尔维斯

var li = document.createElement('link');
    li.type = 'text/css';     
    var href=('https:' == document.location.protocol ? 'https://' : 'http://') +'thesite.com/api/widgets/pages.css';
    li.setAttribute('href', href);
    li.setAttribute('rel','stylesheet');
    var s = document.getElementsByTagName('head')[0];
    s.appendChild(li, s);

我对此所做的更改包括:

  • 我添加了http和https开关以帮助处理不同的连接类型
  • 增加了属性li.setAttribute('rel','stylesheet');〈--我相信这解决了问题。

相关问题