【问题标题】:changing css class model using JavaScript使用 JavaScript 更改 css 类模型
【发布时间】:2012-03-22 21:58:33
【问题描述】:

是否可以使用 JavaScript 更改 css 类模型?

伪代码:

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

className 是类的名称,它应该被更改(如“.footer”),newData 是新的类内容(如边框:“1px solid pink;”)。

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

我不是在寻找更改方式

element.className = "foo";

element.style.fontSize = "15pt";

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

【问题讨论】:

  • 是的,如果您知道规则在哪个样式表中(我猜您可以遍历所有样式表)并且该样式表由 sameDomain 托管

标签: javascript css class model alter


【解决方案1】:

这是我的功能...

    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%");

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    查看我的回答here。回答您的问题:是的,有可能。

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

    【讨论】:

    • 它实际上是样式元素的innerText-attribute(为了完成答案,可以使用 id 或其他方式访问),但它有效 - 非常感谢!
    • 对,该属性似乎与浏览器相关。 IE 似乎需要styleSheets.cssText,其他人对 TextNodes 很幸运。还没试过innerHTML/innerText
    • 关于 Internet Explorer 只有一件事要说:9gag 我猜,innerHTML 行不通 - 毕竟它是 css。
    【解决方案3】:

    据我所知,CSS 对象模型无法轻易告诉您是否已经为特定类设置了现有样式规则,但您可以轻松地为该类添加新规则,它会覆盖该类之前的任何声明风格。

    我找到了creating dynamic stylesheets 的示例。

    【讨论】:

      【解决方案4】:

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

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-01
        • 2016-12-10
        • 1970-01-01
        • 2013-09-02
        • 1970-01-01
        • 1970-01-01
        • 2010-10-08
        • 1970-01-01
        相关资源
        最近更新 更多