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

如何使用JavaScript动态更改样式标记?,javascript,css,Javascript,Css,我想在生成内容后更改样式标记。 如何将样式添加到样式标记? 我尝试使用: document.getElementById('style').appendChild(styleContents); 但它不起作用样式是一种属性。获取ElementById后,可以更改其样式 HTML: 等等。为什么不使用jQuery库并将新CSS直接附加到DOM元素 例如: <script> $(document).ready(function(){ $("#an_element").css("

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

document.getElementById('style').appendChild(styleContents);
但它不起作用

样式是一种属性。获取ElementById后,可以更改其样式

HTML:


等等。

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

例如:

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

<div id="an_element">Test</a>
这将在元素周围添加一个ID为an_元素的边框

试试这个

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(';'));

您可能正在尝试将css添加到样式标记中。这可以通过以下方式实现:

document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here
您还可以使用:

document.styleSheets[0].cssText = ""; //some css goes here
样式元素没有元素子元素,因为就HTML而言,其内容定义为文本。但这意味着您可以使用innerHTML属性将其附加到内容中。如果您的元素具有,则您可以编写:

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

我随口举了一个例子

您可以像在HTML中附加任何其他元素一样,将id附加到样式标记

现在,您可以使用appendChild尝试的代码,并为其添加一个快速更改

document.getElementById'style'.appendChilddocument.createTextNodestyleContents

这应该能奏效。祝你好运


您也可以使用下面列出的innerHTML方法作为我的答案。

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

如果给样式标记一个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
表中的所有类


希望这对别人有帮助

如果要将规则附加到现有样式表中,官方方法是使用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);
            }
        }
    });
};
除了@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;
}

样式标记不应该包含元素您想做什么?更改元素的CSS样式?可能重复:这不正确。他想对样式标记进行更改,这会将内联样式应用于div,这与此无关。嗨,Steve,虽然这是分配属性值的合法方式,但建议您使用内置函数来完成此操作。这是因为不同浏览器呈现HTML和JS的方式不同。就连我以前也这样做过,但面临很多问题,特别是IE。这些是什么内置函数?根据我的经验,修改元素的内容没有问题。这些变化会立即反映出来。但是,我只处理具有一定程度HTML5支持的浏览器,所以我不知道传统浏览器支持动态元素更改的程度。@IanDunn True!我不知道我写这封信时是怎么想的。远离的。
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);
            }
        }
    });
};
// 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;
}