使用JavaScript更改css类模型

changing css class model using JavaScript

本文关键字:模型 css 更改 JavaScript 使用      更新时间:2023-09-26

使用JavaScript更改css类模型有可能吗?

伪代码:

function updateClass(className, newData) {
    cssInterface.alterClass(className, newData);
}

className是应该更改的类的名称(如".footer"),newData是新的类内容(如border:"1px solid pink;")。

实际上,目标只是为了节省空间:我正在使用CSS3动画,因此更改受其类影响的元素的一个属性将终止其动画-(在我的情况下)字体大小将不再更改。使用不同的类将需要为所有受影响的元素创建一组全新的类,我希望避免这种情况。

我没有通过搜索更改

element.className = "foo";

element.style.fontSize = "15pt";

谢谢你们的帮助,伙计们:)

下面是我的函数。。。

    function changeCSS(typeAndClass, newRule, newValue)     // modify the site CSS (if requred during scaling for smaller screen sizes)
{
    var thisCSS=document.styleSheets[0]                                 // get the CSS for the site as an array
    var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules    // work out if the browser uses cssRules or not
    for (i=0; i<ruleSearch.length; i++)                                 // for every element in the CSS array
    {
        if(ruleSearch[i].selectorText==typeAndClass)                    // find the element that matches the type and class we are looking for
        {
            var target=ruleSearch[i]                                    // create a variable to hold the specific CSS element
            var typeExists = 1;
            break;                                                      // and stop the loop
        }
    }
    if (typeExists)
    {
        target.style[newRule] = newValue;                                   // modify the desired class (typeAndClass) element (newRule) with its new value (newValue).
    }
    else
    {
        alert(typeAndClass + " does not exist.");
    }
}

使用(示例)调用

changeCSS("div.headerfixed","-moz-transform-origin", "100% 0%");

希望这能有所帮助。

请在此处查看我的答案。回答你的问题:是的,这是可能的。

@CSS3:我在我的一个html5实验中尝试了完全相同的方法。我创建了一个额外的<style>元素,并将其contentText更改为我需要的CSS类定义。当然,更改cssRule对象会更干净:-)

据我所知,CSS对象模型不能很容易地告诉你是否已经有了特定类的现有样式规则,但你可以很容易地为该类附加一个新规则,它将覆盖该样式以前的任何声明。

我发现了一个创建动态样式表的例子。

你应该看看dojo,它有一些不错的功能,你可以做到这一点。。

require(["dojo/dom-class"], function(domClass){
    // Add a class to some node:
    domClass.add("someNode", "anewClass");
});

http://dojotoolkit.org/reference-guide/1.7/dojo/addClass.html