在客户端,样式表已经是一个对象;当页面加载时,它会被解析成一棵树。
假设您有一个以开头的 HTML 页面
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="/styles/global.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="/styles/catalog.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="/styles/banner.css" rel="stylesheet" type="text/css" media="screen"/>
并global.css
包含行
#page { background-color: #fff; margin-top: 20px; margin-bottom: 20px; text-align: left; width: 100%; margin-top: 20px; padding: 0px; min-width: 900px; border: none; }
#header { background-color: transparent; }
#main { background-color: transparent; margin-left: 10px; margin-right: 10px; padding: 8px 0px 8px 0px;}
#sidebar { margin-right: 12px; }
然后,为了找到为background-color
of设置的内容#page
,您需要编写document.styleSheets[0].cssRules[0].style.backgroundColor
,它将返回#fff
(或者rgb(255, 255, 255)
在某些浏览器上,我认为)。
假设上述表格的其他有用的东西:
document.styleSheets[0].cssRules[3].cssText //"#sidebar { margin-right: 12px; }"
document.styleSheets[0].cssRules[2].selectorText //"#main"
如果您有一个更复杂的选择器,例如#main div.header a, #main div.header a:visited
,则选择器文本属性会返回整个内容,而不仅仅是第一位。
Your specific question is "How can I find out what is set in the stylesheet for a given selector". Here's one way to approximate it:
function findProperty(selector) {
rules = document.styleSheets[0].cssRules
for(i in rules) {
if(rules[i].selectorText==selector) return rules[i].cssText;
}
return false;
}
findProperty('#sidebar'); //returns "#sidebar { margin-right: 12px; }"
The thing is that the CSS tree you have access to in this way has already been parsed by the browser (hence the 'approximate' above). If you're in Firefox, you won't see any -webkit
styles because mozilla just drops them. Various browsers also tend to have their own way of displaying colors (as above; if your actual .css file has a given color set to #fff
, and you check it in JavaScript after it's parsed, you might get back #fff
, #ffffff
or rgb(255, 255, 255)
).
The above will tell you what your browser sees that CSS sheet as; if you want to know what specific ascii characters were contained in the initial .css file, the only reliable way is to look at the file itself, AFAIK.
A reference for the stylesheet object is available here.