开发者

How to locate the element within CSS using javascript

开发者 https://www.devze.com 2023-03-26 06:05 出处:网络
The HTML elements\' position are determined in a linked CSS. 开发者_运维技巧div.title { position:absolute;

The HTML elements' position are determined in a linked CSS.

开发者_运维技巧div.title  
{  
position:absolute;  
top:12px;  
}

I can only use document.styleSheets[0].cssRules[0].position to find the value of the position of the title, but how can I know this position belongs to the title?

In other word, how can the js code know the document.styleSheets[0].cssRules[0] is for the title?


There are a few browser differences when getting styles. To get a style rule generically:

function getStyleRule(s) {
  var sheet, sheets = document.styleSheets;
  var ruleProp, rule, rules;

  for (var i=0, iLen=sheets.length; i<iLen; i++) {
    ruleProp = ruleProp || (sheets[i].cssRules? 'cssRules' : 'rules');
    rules = sheets[i][ruleProp];

    for (var j=0, jLen=rules.length; j<jLen; j++) {
      rule = rules[j];
      if (s == rule.selectorText) {
        return rule;
      }
    }
  }
}

If you just want to match the first rule of the first sheet, then:

var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;
alert( rules[0] );

and to see the selector:

alert( rules[0].selectorText );

and to see the styles that have been set:

alert( rules[0].cssText || rules[0].style.cssText);

Noting that some browsers will return exactly what is written in the style sheet and others will return their interpretation of that (i.e. it is implementation dependent and can't be directly compared across browsers).


you can check if the style is the one you want by iterating the stylesheets then the rules within (two loops)

definitely not very efficient compared to getting computed styles instead, but here's an example

// iterate stylesheets
var css = document.styleSheets;
for (var i in css) {
    if (!isNaN(i)) {
        // iterate rules in the stylesheets
        for (var j in css[i].cssRules) {
            if (!isNaN(j)) {
                var rule = css[i].cssRules[j];
                if (rule.selectorText.indexOf('div.title') > -1) {
                    // do something with position value
                    alert(css[i].cssRules[j].style.position);
                }
            }
        }
    }
}

jsfiddle


I think this answers your question:

You can use document.styleSheets[0].cssRules[0].selectorText which will give you 'div.title'

0

精彩评论

暂无评论...
验证码 换一张
取 消