我正在学习如何使用JavaScript来使CSS更加动态,但由于某些原因,此处的代码无法正常工作。我在Visual Studio中开发,intellisense甚至没有向我展示insertRule方法。作为基础,我使用这个文件进行学习: https://davidwalsh.name/add-rules-stylesheets https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript 我做的和写在那里一样,但不知何故我不能使用该对象的功能。使用JavaScript将规则添加到样式表 - insertRule不工作
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;
};
当您刚创建样式标签时,不需要使用'insertRule'或任何与样式表相关的操作。只要做'style.innerHTML ='css ...'' – adeneo