js 动态添加样式

// 添加 css 脚本
export const loadStyle = url => {
  const link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  const head = document.getElementsByTagName('head')[0];
  head.appendChild(link);
};
// 添加 css 片段

为了节省代码和写出更兼容的代码,有时我们需要用Javascript动态的增加CSS样式。

IE下,我们可以使用 document.createStyleSheet() 方法;而在非IE浏览器上,就不支持这个方法。可以使用document.styleSheets[0],但要求网页里必须最少已经加载过一个样式表。

后来我找到以下方法,可以在Firefox、Opera下正常运行:

var str_css = "body {font-size:12px;}";

var style = document.createElement("style");

style.type = "text/css";

style.innerHTML = str_css;

document.getElementsByTagName("HEAD").item(0).appendChild(style);

但这种方法却在Safari、Chrome下不可行,原因是style.innerHTML不可写。我再找解决方案,发现用textContent代替innerHTML的方法可行。

最后,我发个原创JS动态增加CSS样式的方法,兼容目前流行的任意浏览器:

function add_css(str_css) { //Copyright @ rainic.com

try { //IE下可行

var style = document.createStyleSheet();

style.cssText = str_css;

}

catch (e) { //Firefox,Opera,Safari,Chrome下可行

var style = document.createElement("style");

style.type = "text/css";

style.textContent = str_css;

document.getElementsByTagName("HEAD").item(0).appendChild(style);

}

}
————————————————
版权声明:本文为CSDN博主「hdxx2022」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hdxx2022/article/details/129499950
posted @ 2023-06-03 12:25  whmmm  阅读(223)  评论(0)    收藏  举报
//增加一段JS脚本,为目录生成使用