如何将新规则添加到现有CSS类

时间:2013-08-24 18:49:53

标签: javascript css class dynamic stylesheet

在下面的代码中,我已经说明了我想要实现的目标...... 通过向其添加新规则来更改现有的CSS类。

<head>
<style> 

h4.icontitle
{font-size: 22pt;}

</style>
</head>
<body>
<script type="text/javascript">

textpercent = 84;
document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null);

</script>

<h4> hello </h4>

</body>

这适用于在不同大小的屏幕上运行的网站的预处理元素。 结果将是......

h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}

检查DOM时可以看到。

任何想法都会受到欢迎。仅限Javascript - 此处没有JQuery ...

解决。

经过大量的试验和错误,这是一个允许javascript直接将样式插入CSS的工作函数

function changeCSS(typeAndClass, newRule, newValue)
{
    var thisCSS=document.styleSheets[0]
    var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
    for (i=0; i<ruleSearch.length; i++)
    {
        if(ruleSearch[i].selectorText==typeAndClass)
        {
            var target=ruleSearch[i]
            break;
        }
    }
    target.style[newRule] = newValue;
}

调用
    changeCSS("h4.icontitle","backgroundColor", "green");

希望其他人会发现这是一种在纯CSS中使用CSS中的变量的有用方法。

4 个答案:

答案 0 :(得分:2)

我举了一个适合你需要的例子

DEMO jsFiddle

// this gets all h4 tags
var myList = document.getElementsByTagName("h4"); // get all p elements

// this loops through them until it finds one with the class 'icontitle' then it assigns the style to it
var i = 0;
while(i < myList.length) {
    if(myList[i].className == "icontitle") {
        myList[i].style.color="red";
    }
    i++;
}

答案 1 :(得分:1)

此功能适用于我的网站。

function changeCSS(typeAndClass, newRule, newValue)
{
    var thisCSS=document.styleSheets[0]
    var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
    for (i=0; i<ruleSearch.length; i++)
    {
        if(ruleSearch[i].selectorText==typeAndClass)
        {
            var target=ruleSearch[i]
            break;
        }
    }
    target.style[newRule] = newValue;
}

调用
    changeCSS("h4.icontitle","backgroundColor", "green");

答案 2 :(得分:0)

/**
Use this to update style tag contents
**/
var css = 'h1 { background: grey; }',
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);

使用body使用querySelector中的元素来定位其CSS标识符上的元素。这应该对你有帮助 https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

var el = document.querySelector(".icontitle");
el.setAttribute("style","-webkit-text-size-adjust:84%");

或者你可以准备一个css片段并有条件地使用ex:如果“new_css”是新的变化那么

/**css code in style tag**/
.icontitle{

  /**style at initial stage**/

}
.icontitle-new-modified{

 /**modified css style at later stage**/

}

//after a condition is satisfied
el.setAttribute("class","icontitle-new-modified");

答案 3 :(得分:-1)

试试这段代码

$('h4.icontitle').css('-webkit-text-size-adjust','84%');