如何向现有 CSS 类添加新规则

TJS*_*101 5 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>
Run Code Online (Sandbox Code Playgroud)

这是针对在不同尺寸的屏幕上运行的站点的预处理元素。结果将是...

h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}
Run Code Online (Sandbox Code Playgroud)

在检查 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;
}
Run Code Online (Sandbox Code Playgroud)

    changeCSS("h4.icontitle","backgroundColor", "green");
Run Code Online (Sandbox Code Playgroud)

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

Kev*_*nch 1

我整理了一个适合您需求的示例

演示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++;
}
Run Code Online (Sandbox Code Playgroud)