我想在生成内容后更改样式标签。 如何向样式标签添加样式? 我尝试使用:
document.getElementById('style').appendChild(styleContents);
但它没有起作用。
我想在生成内容后更改样式标签。 如何向样式标签添加样式? 我尝试使用:
document.getElementById('style').appendChild(styleContents);
但它没有起作用。
你可能正在尝试将CSS添加到样式标签中。可以使用以下方法完成:
document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here
您也可以使用:
document.styleSheets[0].cssText = ""; //some css goes here
我知道这是一个旧问题,但我一直在尝试找到一种方法来动态更新这些元素,而不必直接应用样式。
如果你给一个样式标签一个ID并选择它,你就可以使用sheet属性访问它的CSS。
从这里开始,你可以更新任何你想要的东西。通过替换标签内的整个CSS或更新单个类别。
document.getElementById('somestyletagid').sheet.cssRules[0].selectorText
这是您的类选择器。
document.getElementById('somestyletagid').sheet.cssRules[0].style
这些是该类的所有个别CSS属性。
您可以通过执行以下操作更新背景颜色:
document.getElementById('somestyletagid').sheet.cssRules[0].style.backgroundColor = 'red'
这是一种访问 HTML 中任何样式标签的方法。不幸的是,我找不到每个 CSSStyleRule 的严格唯一 ID,最接近的是 selectorText,但显然它可能会重复。无论如何,至少对于我的需求,这正是我所需要的。
您还可以使用 document.styleSheets 并以通常相同的方式访问它们来更新任何已包含的 CSS 文件。
document.styleSheets[0].href
所包含的CSS文件的href。
document.styleSheets[0].cssRules
所有表格中的类。
希望这能对某人有所帮助!
style
元素没有任何子元素,因为根据HTML的定义,它的内容只是文本。但这意味着您可以使用 innerHTML
属性直接附加到其内容。如果您的元素有 <style id=foo>
,则可以编写:
document.getElementById('foo').innerHTML += styleContents;
<style id="style"></style>
现在,您可以将尝试使用appendChild的代码添加一个快速更改。
document.getElementById('style').appendChild(document.createTextNode(styleContents));
这应该就可以解决问题了。祝你好运。var currentElement = document.getElementById('style');
var currentStyle = currentElement.getAttribute('style');
var stylePieces = [];
if(currentStyle) {
stylePieces = currentStyle.split(';');
}
stylePieces.push('new-style: true;');
currentElement.setAttribute('style', stylePieces.join(';'));
为什么不使用jQuery库并直接将新的CSS附加到DOM元素上呢?
例如:
<script>
$(document).ready(function(){
$("#an_element").css("border", "1px solid #333");
});
</script>
<div id="an_element">Test</a>
在 @AtheistP3ace
的回答基础上,这里有一个使用纯 JavaScript 改变样式块内容的函数:
// Change the CSS in the style section.
// Property is the name of the class or id E.G. ".mdc-card" or "#main".
// Style is the name of the CSS style. E.G. "Background".
// Value is the setting that the style will use, E.G. "Red"
// WARNING: STOPS AND EXECUTES ON THE FIRST MATCH DOES NOT PROCESS MORE AFTER THAT!!!
function changeCSS(property, style, value, cssSectionID) {
if (cssSectionID === undefined) {
cssSectionID = "mainCSS";
}
// Get the current CSS sheet.
var mainCSS = document.getElementById("mainCSS");
var changeStatus = false;
// Refine the stylesheet into a more easily processed form.
// It is done here as making it part of the variable definition produces issues where you still need to call the sheet property.
mainCSS = mainCSS.sheet;
// Only execute if the user has specified values for each of the required parameters.
if (property !== undefined && style !== undefined && value !== undefined) {
// Loop through all of the CSS Properties until the specified property is found.
for (var index = 0; index < mainCSS.cssRules.length; index++) {
// Only apply the value of the property matches.
if (mainCSS.cssRules[index].selectorText === property.toString()) {
// Apply the specified property value to the.
mainCSS.cssRules[index].style[style.toString()] = value.toString();
// Sets the exit status and breaks the loop's execution.
changeStatus = true;
break;
}
}
}
// Returns the result of the operation. True being successful and false being unsuccessful.
return changeStatus;
}
function AddMoreStyles(code, styleTagId) {
var sheet = document.getElementById('#' + styleTagId);
let lines = code.replace(/[\r\n\t]/gm, ' ').split(/}/);
if (!sheet) {
return;
}
sheet = sheet.styleSheet || sheet.sheet || sheet;
lines.forEach(function (str) {
str = $.trim(str) + '}';
let m = str.match(/(.+?)\{(.*?)}/), m1, m2;
if (m) {
m1 = $.trim(m[1]);
m2 = $.trim(m[2]);
try {
if (sheet.insertRule) sheet.insertRule(m1 + '{' + m2 + '}', sheet.cssRules.length);
else sheet.addRule(m1, m2);
} catch (e) {
console.log("!ERROR in css rule: " + e.message);
}
}
});
};