繁体   English   中英

JavaScript 通过名称访问 CSS 类?

[英]JavaScript access CSS class by its name?

我必须按名称访问 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 行中描述的那样访问我不想通过页面上的单个元素访问,而是通过类名直接访问样式表。

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

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

// 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属性,您首先应该检查声明是否存在。

是的,贝尔吉是对的:
您首先必须为样式列表建立一个索引。
但要注意:
如果有多个样式表,您首先必须遍历样式表 所以我喜欢改进 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";
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')    

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

// 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小提琴演示

还有一个稍微改进的替代方案(一个对象而不是两个数组,需要 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小提琴演示

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

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

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

别的:

document.querySelector(".className");

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

Quirksmode CSSOM (DOM CSS) 兼容性表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM