使用 JavaScript 向样式表添加规则 - insertRule 不起作用

Roa*_*991 0 javascript css webpage

我正在学习使用JavaScript使CSS更加动态,但由于某种原因,这里的代码不起作用。我在Visual Studio 中进行开发,IntelliSense 甚至没有向我显示方法 insertRule。作为基础,我使用此文档进行学习:

https://davidwalsh.name/add-rules-stylesheets

https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

我和那里写的一样,但不知何故我不能在对象上使用该函数。

window.onload = function() {
    var bar = newSheet();
    bar.insertRule("header { float: left; opacity: 0.8; }", 1);  
};

function newSheet() {
    // Create the <style> tag
    var style = document.createElement("style");
    //WebKit Hack
    style.appendChild(document.createTextNode(""));
    // Add the <style> element to the page
    document.head.appendChild(style);

    return style.sheet;
};
Run Code Online (Sandbox Code Playgroud)

Ern*_*zas 5

Elementstyle就像任何其他 DOM 标签一样工作,因此,您可以使用 innerHTML 向其附加样式,因为您已经从 javascript 创建了该元素,您只需要修改其值:

window.onload = function() {
  var bar = newSheet();
  bar.insertRule("header { float: left; opacity: 0.8; }", 1);  
};

function newSheet() {
 // Create the <style> tag
 var style = document.createElement("style");

 style.innerHTML="p{color:red;}";
 style.innerHTML+="h1{color:green;}";

 //WebKit Hack
 style.appendChild(document.createTextNode(""));
 // Add the <style> element to the page
 document.head.appendChild(style);

 return style.sheet;
};
Run Code Online (Sandbox Code Playgroud)