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

9
在下面的代码中,我已经说明了我想要实现的内容...通过向现有的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");

希望其他人能够发现这是一种有用的方法,在纯JavaScript中使用变量来编写CSS。


你想使用JavaScript或jQuery来修改CSS,对吧? - iJade
1
为什么不使用jQuery或类似的库呢?$('h4.icontitle').css('-webkit-text-size-adjust', textpercent+'%'); - Sergiu Paraschiv
此网站目前仅使用纯Javascript,没有任何库。 - TJS101
已解决。请查看问题的编辑。 - TJS101
4个回答

4

这个函数在我的网站上完美运行。

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
/**
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代码片段,并有条件地使用它,例如:如果“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");

document.querySelector(".icontitle") 返回了一个空值。你确定这是正确的吗?谢谢。 - TJS101
啊,它正在定位身体中的元素,而不是CSS。 我需要这个来改变头部的CSS。 请参见原始问题中的期望输出。 - TJS101
你可以创建备用的CSS片段,并使用querySelector更改元素的class属性,这样你甚至可以管理你的代码并实现你想要的效果。 - art-fan-vikram
元素未定义。内容是动态提供的。我需要修改CSS而不是元素样式。 - TJS101
2
我已经修改了答案,请检查,希望能有所帮助。 - art-fan-vikram
你让我找到了正确的方向。我已经留下了一个完全可用的函数,可以在我的问题编辑中实现我想要的功能。谢谢。 - TJS101

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

逻辑是相同的,很高兴我能帮助到你。 - Kevin Lynch
1
只是为了明确,这个答案解决的问题略有不同:改变特定选择器的CSS样式,而不是创建不同的CSS规则。如果您稍后将新的h4.icontitle元素添加到DOM中,则可以看到差异。在TJS101对自己问题给出的答案中,新元素将具有更改后的样式,而在此解决方案中,它不会。 - Denise Draper

-2

试试这段代码

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

我没有使用JQuery,只用JS。这看起来很棒。JS的等效代码是什么? - TJS101
1
纯JS中重要且复杂的部分是:$('h4.icontitle')。为什么呢?基本上,您需要遍历整个DOM树并查找所有具有该类别的h4标签,并构建一个列表。 - Sergiu Paraschiv
请查看原始问题中的代码片段。那就是我想要让它工作的东西。 - TJS101
1
与Vector的答案一样,这并不是TJS101提出的同一个问题的解决方案。它确实会设置所有当前的h4.icontitle元素的样式,但如果稍后创建了新的h4.icontitle元素,它们将无法像更改css规则那样拾取样式。显然,这可能重要或不重要,具体取决于情况。 - Denise Draper

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