简体   繁体   English

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

[英]How to dynamically change the style tag using JavaScript?

I want to change the style tag after generating contents. 我想在生成内容后更改样式标记。 How can I add style to the style tag? 如何在样式标记中添加样式? I tried using: 我试过用:

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

but it did not work 但它不起作用

You are probably trying to add css to the style tag. 您可能正在尝试将css添加到样式标记中。 This can be accomplished using: 这可以使用以下方法完成:

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

You can also use: 您还可以使用:

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

I know this is an old question but I have been trying to figure out a way to dynamically update these as well without applying styling directly to the element. 我知道这是一个古老的问题,但我一直试图找到一种方法来动态更新这些,而无需直接对元素应用样式。

If you give a style tag an ID and select it you can then access its CSS using sheet property. 如果为样式标记指定ID并选择它,则可以使用sheet属性访问其CSS。

From here you can update anything you want. 从这里你可以更新你想要的任何东西。 By replacing the entire CSS inside the tag or updating individual classes. 通过替换标记内的整个CSS或更新单个类。

document.getElementById('somestyletagid').sheet.cssRules[0].selectorText

This is your class selector. 这是您的班级选择器。

document.getElementById('somestyletagid').sheet.cssRules[0].style

These are are all the individual css properties on that class. 这些是该类的所有单独的css属性。

You can update the background color by doing this: 您可以通过执行以下操作更新背景颜色:

document.getElementById('somestyletagid').sheet.cssRules[0].style.backgroundColor = 'red'

This is a way to access any style tags in your html. 这是一种访问html中任何样式标记的方法。 Unfortunately there is no strictly unique ID for each CSSStyleRule that I can find. 不幸的是,我找不到每个CSSStyleRule的严格唯一ID。 Closest is the selectorText but obviously that can be repeated. 最接近的是selectorText,但显然可以重复。 Either way at least for my needs this does exactly what I need. 无论哪种方式,至少对我的需求,这正是我所需要的。

You can also update any included CSS files by using document.styleSheets and accessing them in generally the same way. 您还可以使用document.styleSheets更新任何包含的CSS文件,并以相同的方式访问它们。

document.styleSheets[0].href

The href of the included css file. 包含的css文件的href。

document.styleSheets[0].cssRules

All the classes in the sheet. 工作表中的所有类。

Hope this helps someone! 希望这有助于某人!

style is a property. style是一种财产。 After you getElementById() you can change its style . getElementById()您可以更改其style

HTML: HTML:

<div id='myDiv'>...</div>

JS: JS:

var div = document.getElementById('myDiv')

div.style.background = 'red';
div.style.margin = "10px";
div.style.fontSize = "12px";

etc. 等等

A style element has no element children, as its content is by definition just text (as far as HTML is concerned). style元素没有元素子元素,因为它的内容按照定义只是文本(就HTML而言)。 But this means that you can just append to its content using the innerHTML property. 但这意味着您可以使用innerHTML属性附加到其内容。 If your element has <style id=foo> , then you write: 如果你的元素有<style id=foo> ,那么你写:

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

I tossed together a quick example at http://jsfiddle.net/fttS5/1/ . 我在http://jsfiddle.net/fttS5/1/上拼了一个简单的例子。

You can attach an id to the style tags just like you would any other element in HTML. 您可以将id附加到样式标记,就像在HTML中的任何其他元素一样。

<style id="style"></style>

Now you can take the code you tried with appendChild and add one quick change to it 现在,您可以使用appendChild获取您尝试的代码,并为其添加一个快速更改

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

This should do the trick. 这应该可以解决问题。 Good Luck. 祝好运。

You can also just use the innerHTML method listed as the answer below mine. 您也可以使用下面列出的innerHTML方法作为我的答案。

try this 尝试这个

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

Why don't you use the jQuery library and append new CSS to the DOM elements directly? 为什么不使用jQuery库并直接将新的CSS附加到DOM元素?

For example: 例如:

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

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

This would add a border around your element with the ID "an_element". 这将使用ID“an_element”在元素周围添加边框。

jQuery Selectors jQuery选择器

jQuery CSS jQuery CSS

If you want to append rules to an existing style sheet, the official way to do is with the insertRule methods. 如果要将规则附加到现有样式表,正式的方法是使用insertRule方法。 It will probably be alot easier on the browser then just appending text. 浏览器可能会更容易,只需添加文本即可。 Also if you do it like below, if there is a particular css rule is not valid syntax, it will skip it, thus protecting the integrity of your document. 此外,如果你这样做,如果有一个特定的CSS规则是无效的语法,它将跳过它,从而保护文档的完整性。

Uses jQuery just for string timming, probably not needed anyway. 使用jQuery只是为了字符串调整,可能不需要。

You have to give it the ID of the style tag. 你必须给它样式标签的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);
            }
        }
    });
};

Adding onto @AtheistP3ace 's answer, here is a function that uses pure JavaScript to change the content of a style block: 添加到@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM