使用 jQuery 将样式表添加到文档中

Adding a Style Sheet to a document using jQuery

本文关键字:文档 添加 jQuery 样式 使用      更新时间:2023-09-26
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">');    
    });

上面的代码是我用来将样式表添加到文档中的代码。代码检查器显示代码已添加,但控制台不显示浏览器已请求文档且样式不起作用。

如何将样式表添加到已加载的文档并使其生效。

顺便说一句,如果这很重要,我正在将此代码用于小部件,因此我将在多个域中使用。

提前感谢您的任何帮助!

试试这个:

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

好的,在做了一些测试之后,我终于弄清楚发生了什么。此原始代码由以下人员提供: @Vicky Gonsalves

    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'(; <-- 我相信这解决了这个问题。