欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript获取指定名字的样式规则

程序员文章站 2022-05-17 22:18:36
...
function getCSSRule(ruleSelectorText, styleSheetHref) {
	var doc = document,
		styleSheets = doc.styleSheets,
		rules = [],
		styleSheet, rule,
		i, j, len, len2;
	for (i = 0, len = styleSheets.length; i < len; i++) {
			styleSheet = styleSheets[i];
			if (styleSheetHref) {
				if (styleSheet.href.indexOf(styleSheetHref) === -1) {
					continue;
				}
			}
			for (j = 0, len2 = styleSheet.rules.length; j < len2; j++) {
				rule = styleSheet.rules[j];
				if (rule.selectorText === ruleSelectorText) {
					return rule;
				}
			}
	}
	return null;
}


参数说明:
ruleSelectorText
样式类名,比如".myDiv", ".test"

styleSheetHref
样式文件的URL, 比如http://localhost/myWebApp/resources/my.css

用法举例:
getCSSRule(".x-button")
返回样式".x-button" object.