[英]How to locate the element within CSS using javascript
The HTML elements' position are determined in a linked CSS. HTML元素的位置在链接的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? 我只能使用
document.styleSheets[0].cssRules[0].position
查找标题位置的值,但是我怎么知道这个位置属于标题呢?
In other word, how can the js code know the document.styleSheets[0].cssRules[0]
is for the title? 换句话说,js代码如何知道
document.styleSheets[0].cssRules[0]
是标题?
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 (ie it is implementation dependent and can't be directly compared across browsers). 请注意,某些浏览器将完全返回样式表中编写的内容,而其他浏览器将返回其解释(即,它依赖于实现,并且不能在各个浏览器之间直接进行比较)。
I think this answers your question: 我认为这可以回答您的问题:
You can use document.styleSheets[0].cssRules[0].selectorText
which will give you 'div.title' 您可以使用
document.styleSheets[0].cssRules[0].selectorText
来给您“ div.title”
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);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.