如何使用JavaScript动态更改样式标签?

18

我想在生成内容后更改样式标签。 如何向样式标签添加样式? 我尝试使用:

document.getElementById('style').appendChild(styleContents);

但它没有起作用。


样式标签不应包含元素。 - Asad Saeeduddin
你想要做什么?改变一个元素的 CSS 样式吗? - danwellman
可能重复:https://dev59.com/l3RB5IYBdhLWcg3wv5tA - Luca Borrione
8个回答

30

你可能正在尝试将CSS添加到样式标签中。可以使用以下方法完成:

document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here

您也可以使用:

document.styleSheets[0].cssText = ""; //some css goes here

23

我知道这是一个旧问题,但我一直在尝试找到一种方法来动态更新这些元素,而不必直接应用样式。

如果你给一个样式标签一个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

所有表格中的类。

希望这能对某人有所帮助!


5

style 元素没有任何子元素,因为根据HTML的定义,它的内容只是文本。但这意味着您可以使用 innerHTML 属性直接附加到其内容。如果您的元素有 <style id=foo>,则可以编写:

document.getElementById('foo').innerHTML += styleContents;

4
我在http://jsfiddle.net/fttS5/1/上快速制作了一个示例。
您可以像使用HTML中的任何其他元素一样,向style标签附加id。 <style id="style"></style> 现在,您可以将尝试使用appendChild的代码添加一个快速更改。 document.getElementById('style').appendChild(document.createTextNode(styleContents)); 这应该就可以解决问题了。祝你好运。
您还可以使用下面我回答中列出的innerHTML方法。

3
尝试一下。
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(';'));

2

为什么不使用jQuery库并直接将新的CSS附加到DOM元素上呢?

例如:

<script>
$(document).ready(function(){
    $("#an_element").css("border", "1px solid #333");
});
</script>

<div id="an_element">Test</a>

这将在具有ID“an_element”的元素周围添加边框。 jQuery选择器 jQuery CSS

0

@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;
}

0
如果您想将规则附加到现有样式表中,则官方的方法是使用insertRule方法。这可能比仅附加文本对浏览器更容易。此外,如果您像下面这样做,如果特定的CSS规则不是有效语法,则会跳过它,从而保护文档的完整性。
仅使用jQuery进行字符串修剪,可能不需要。
您必须为其提供样式标签的ID。
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);
            }
        }
    });
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接