【问题标题】:JavaScript access CSS class by its name?JavaScript 通过名称访问 CSS 类?
【发布时间】:2012-10-22 22:22:40
【问题描述】:

我必须按名称访问 CSS 类,下面的代码有效。但是,如果我尝试 hui["myclass"]hui[".myclass"] 而不是 hui[0] 它找不到它。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <style>
      .myclass {
        color: #00aa00;
      }
    </style>
    <script type="text/javascript">
        function change_class() {
          var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
          hui[0].style["color"]="#ff0000"
        }
    </script>
  </head>
  <body>
    <div class="myclass" onclick="change_class()">Some Text</div>
  </body>
</html>

编辑:我需要能够像我在第 1 行中描述的那样访问我不想通过页面上的单个元素访问,而是直接按类名访问样式表。

所以你们都说我不能只通过索引通过类名访问样式表?

【问题讨论】:

  • 那是因为0 是一个索引。
  • 我如何通过名称访问?
  • 你不能只用jQuery和$('.myclass').trigger()吗?
  • 不知道它的支持级别,但querySelectorAll() 是一个选项。
  • document.getElementByClassName() 是另一种方式。

标签: javascript css properties


【解决方案1】:

不,您不能通过选择器访问它们 - 这是一个简单的列表。你首先必须为它建立一个索引:

// assuming those are the right rules (ie from the right stylesheet)
var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;

var styleBySelector = {};
for (var i=0; i<hui.length; i++)
    styleBySelector[hui[i].selectorText] = hui[i].style;

// now access the StyleDeclaration directly:
styleBySelector[".myclass"].color = "#ff0000";

当然这不是万无一失的方法,可能有

  • 多个选择器,例如.myClass, .myOtherClass
  • 一个选择器多次出现(尽管没关系,最后一个声明会覆盖以前的样式)

而不是盲目地分配 color 属性,您首先应该检查声明是否存在。

【讨论】:

    【解决方案2】:

    是的,Bergi 是对的:
    您首先必须为样式列表建立索引。
    但要小心:
    如果有超过 1 个样式表,您首先必须遍历样式表。 所以我喜欢改进 Bergis 解决方案:

    var styleBySelector = {};
    for (var j=0; j<document.styleSheets.length; j++)   {
      var styleList = document.styleSheets[j].rules || document.styleSheets[j].cssRules;
      for (var i=0; i<styleList.length; i++)
        styleBySelector[styleList[i].selectorText] = styleList[i].style;
     }
    
    // And then invoke or set the style you wish like this:
    styleBySelector[".myStyle"].color = "#ff0000";
    

    【讨论】:

      【解决方案3】:
      document.getElementsByClassName('myclass');
      

      将返回一个匹配的元素数组。

      你也可以使用类似的东西:

      <body>
          <div id="changethese">
              <div class="myclass" onclick="change_class()">Some Text</div>
          </div>
          <div class="myclass">div two</div>
      </body>
      

      Javascript:

      var changeTheseDivs = document.getElementById('changethese');
      changeTheseDivs.getElementsByClassName('myclass')
      

      仅更改所选 div 中的类。

      但是,对这种方法的支持只适用于 IE9,所以如果 JQuery 是一个选项,最好使用它。

      编辑:

      我相信我看错了,看起来您想更改实际的 CSS 规则本身,而不是更改元素上的 CSS。理论上,您可以编写一个函数,为您按名称查找规则并更改它们的属性。我猜它看起来像这样(未经测试,应该可以):

      function findAndChangeCSSRule(ruleName, newRule, newProperty){
          var mysheet=document.styleSheets[0];
          var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules
          for (i=0; i<myrules.length; i++){
              if(myrules[i].selectorText.toLowerCase()==ruleName){
                   targetrule=myrules[i];
                   break;
              }
          }
          targetrule.style[newRule.toString()]=newProperty;
      }
      

      然后调用它:

      findAndChangeCSSRule('my_class', 'color', 'red')    
      

      【讨论】:

      • 我不想通过任何元素访问。
      • 我看到很抱歉误读,请查看编辑,它至少应该让你开始。
      • @JohnSmith Trough 在这种情况下到底意味着什么?我假设您的意思是-通过-,因为水槽是一个食物容器,除此之外与代码无关。
      • @Daedalus 他想操作样式表,而不是内联样式。
      • 我认为你不应该使用toLowerCase,这可能会产生巨大的影响
      【解决方案4】:

      要改变既定规则,这是一种方法:

      // the [2] index is only because that's where JS Fiddle
      // puts the user-entered CSS (from the CSS panel).
      var sheets = document.styleSheets[2].rules,
          classString = 'body',
          props = ['color'], // requires a 1:1 relationship between two arrays...ugh
          to = ['#0f0'];
      
      for (var i = 0, len = sheets.length; i < len; i++) {
          if (sheets[i].selectorText == classString) {
              for (var c = 0, leng = props.length; c < leng; c++) {
                  sheets[i].style[props[c]] = to[c];
              }
          }
      }​
      

      JS Fiddle demo.

      还有一个稍微改进的替代方案(一个对象而不是两个数组,需要 1:1 的关系):

      var sheets = document.styleSheets[2].rules,
          classString = 'body',
          propsTo = {
              'color': '#0f0'
          };
      
      for (var i = 0, len = sheets.length; i < len; i++) {
          if (sheets[i].selectorText == classString) {
              for (var prop in propsTo) {
                  if (propsTo.hasOwnProperty(prop)) {
                      sheets[i].style[prop] = propsTo[prop];
                  }
              }
          }
      }​
      

      JS Fiddle demo.

      【讨论】:

        【解决方案5】:

        要从 javascript 访问该类,您只需要创建一个分类器,如果它不存在。

        document.querySelector("myDiv").classList.add("className");
        

        这会将新类添加到具有指定类名的 div 中。

        其他:

        document.querySelector(".className");
        

        【讨论】:

          【解决方案6】:

          (document.styleSheets[0].cssRules || document.styleSheets[0].rules)[0].style.color = '#ff0000' 应该可以。

          Quirksmode CSSOM (DOM CSS) compatibility table

          【讨论】:

          • 这就是我现在开始的不同格式而不是 [0] 我需要名称,请下次仔细阅读。
          猜你喜欢
          • 2016-07-05
          • 2018-02-19
          • 2012-02-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-18
          相关资源
          最近更新 更多