jQuery-如何使用元素的HTML获取所有样式 css(在内部外部文档中定义)

jQuery-如何使用元素的HTML获取所有样式 css(在内部外部文档中定义),第1张

jQuery-如何使用元素的HTML获取所有样式/ css(在内部/外部文档中定义)

(不确定,以防万一)

局限性:使用CSSOM,样式表应来自同一来源。

function getElementChildrenAndStyles(selector) {  var html = $(selector).outerHTML();  selector = selector.split(",").map(function(subselector){    return subselector + "," + subselector + " *";  }).join(",");  elts = $(selector);  var rulesUsed = [];  // main part: walking through all declared style rules  // and checking, whether it is applied to some element  sheets = document.styleSheets;  for(var c = 0; c < sheets.length; c++) {    var rules = sheets[c].rules || sheets[c].cssRules;    for(var r = 0; r < rules.length; r++) {      var selectorText = rules[r].selectorText;      var matchedElts = $(selectorText);      for (var i = 0; i < elts.length; i++) {        if (matchedElts.index(elts[i]) != -1) {          rulesUsed.push(rules[r]); break;        }      }    }  }  var style = rulesUsed.map(function(cssRule){    if (cssRule.style) {      var cssText = cssRule.style.cssText.toLowerCase();    } else {      var cssText = cssRule.cssText;    }    // some beautifying of css    return cssText.replace(/({|;)s+/g, "n  ").replace(/As+}/, "}");    //      set indent for css here ^   }).join("n");  return "<style>n" + style + "n</style>nn" + html;}

用法

getElementChildrenAndStyles("#divId");


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5559668.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存