Dio*_*ane 106 html javascript css
我想返回一个包含CSS规则所有内容的字符串,就像您在内联样式中看到的格式一样.我希望能够在不知道特定规则中包含的内容的情况下执行此操作,因此我不能仅通过样式名称将其拉出(如.style.width等)
CSS:
.test {
width:80px;
height:50px;
background-color:#808080;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止的代码:
function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<classes.length;x++) {
if(classes[x].selectorText==className) {
//this is where I can collect the style information, but how?
}
}
}
getStyle('.test')
Run Code Online (Sandbox Code Playgroud)
小智 81
改编自这里,建立在scunliffe的回答:
function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
(classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
}
}
}
getStyle('.test');
Run Code Online (Sandbox Code Playgroud)
dud*_*ude 22
由于"nsdel"中接受的答案仅适用于文档中的一个样式表,因此这是经过调整的完整工作解决方案:
/**
* Gets styles by a classname
*
* @notice The className must be 1:1 the same as in the CSS
* @param string className_
*/
function getStyle(className_) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
if (!classes)
continue;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
if (classes[x].selectorText == className_) {
var ret;
if(classes[x].cssText){
ret = classes[x].cssText;
} else {
ret = classes[x].style.cssText;
}
if(ret.indexOf(classes[x].selectorText) == -1){
ret = classes[x].selectorText + "{" + ret + "}";
}
return ret;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:选择器必须与CSS中的相同.
T.T*_*dua 16
function GetProperty(classOrId,property)
{
var FirstChar = classOrId.charAt(0); var Remaining= classOrId.substring(1);
var elem = (FirstChar =='#') ? document.getElementById(Remaining) : document.getElementsByClassName(Remaining)[0];
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
alert( GetProperty(".my_site_title","position") ) ;
Run Code Online (Sandbox Code Playgroud)
function GetStyle(CLASSname)
{
var styleSheets = document.styleSheets;
var styleSheetsLength = styleSheets.length;
for(var i = 0; i < styleSheetsLength; i++){
if (styleSheets[i].rules ) { var classes = styleSheets[i].rules; }
else {
try { if(!styleSheets[i].cssRules) {continue;} }
//Note that SecurityError exception is specific to Firefox.
catch(e) { if(e.name == 'SecurityError') { console.log("SecurityError. Cant readd: "+ styleSheets[i].href); continue; }}
var classes = styleSheets[i].cssRules ;
}
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == CLASSname) {
var ret = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText ;
if(ret.indexOf(classes[x].selectorText) == -1){ret = classes[x].selectorText + "{" + ret + "}";}
return ret;
}
}
}
}
alert( GetStyle('.my_site_title') );
Run Code Online (Sandbox Code Playgroud)
一些浏览器差异需要注意:
鉴于CSS:
div#a { ... }
div#b, div#c { ... }
Run Code Online (Sandbox Code Playgroud)
在InsDel的例子中,类将在FF中有2个类,在IE7中有3个类.
我的例子说明了这一点
<!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" xml:lang="en" lang="en">
<head>
<style>
div#a { }
div#b, div#c { }
</style>
<script>
function PrintRules() {
var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<rules.length;x++) {
document.getElementById("rules").innerHTML += rules[x].selectorText + "<br />";
}
}
</script>
</head>
<body>
<input onclick="PrintRules()" type="button" value="Print Rules" /><br />
RULES:
<div id="rules"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我发现没有任何建议可以真正起作用。这是一个更强大的方法,可以在查找类时规范间距。
//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
function normalize(str) {
if (!str) return '';
str = String(str).replace(/\s*([>~+])\s*/g, ' $1 '); //Normalize symbol spacing.
return str.replace(/(\s+)/g, ' ').trim(); //Normalize whitespace
}
function split(str, on) { //Split, Trim, and remove empty elements
return str.split(on).map(x => x.trim()).filter(x => x);
}
function containsAny(selText, ors) {
return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
}
return function (selector) {
const logicalORs = split(normalize(selector), ',');
const sheets = Array.from(window.document.styleSheets);
const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
};
})();
Run Code Online (Sandbox Code Playgroud)
这是 Chrome 控制台中的操作。