짧은 버전 2017 년 4 월 12 일
도전자가 나타납니다.
var getMatchedCSSRules = (el, css = el.ownerDocument.styleSheets) =>
[].concat(...[...css].map(s => [...s.cssRules||[]]))
.filter(r => el.matches(r.selectorText));
Line /* 1 */은 모든 규칙의 평면 배열을 만듭니다.
라인 /* 2 */은 일치하지 않는 규칙을 버립니다.
동일한 페이지에서 @SB의 기능css(el) 을 기반으로 합니다 .
예 1
var div = iframedoc.querySelector("#myelement");
var rules = getMatchedCSSRules(div, iframedoc.styleSheets);
console.log(rules[0].parentStyleSheet.ownerNode, rules[0].cssText);
예 2
var getMatchedCSSRules = (el, css = el.ownerDocument.styleSheets) =>
[].concat(...[...css].map(s => [...s.cssRules||[]]))
.filter(r => el.matches(r.selectorText));
function Go(big,show) {
var r = getMatchedCSSRules(big);
PrintInfo:
var f = (dd,rr,ee="\n") => dd + rr.cssText.slice(0,50) + ee;
show.value += "--------------- Rules: ----------------\n";
show.value += f("Rule 1: ", r[0]);
show.value += f("Rule 2: ", r[1]);
show.value += f("Inline: ", big.style);
show.value += f("Computed: ", getComputedStyle(big), "(…)\n");
show.value += "-------- Style element (HTML): --------\n";
show.value += r[0].parentStyleSheet.ownerNode.outerHTML;
}
Go(...document.querySelectorAll("#big,#show"));
.red {color: red;}
#big {font-size: 20px;}
<h3 id="big" class="red" style="margin: 0">Lorem ipsum</h3>
<textarea id="show" cols="70" rows="10"></textarea>
단점
- 미디어 처리 없음
@import ,, @media.
- 교차 도메인 스타일 시트에서로드 된 스타일에 액세스 할 수 없습니다.
- 선택기 "특이성"(중요도 순서)으로 정렬하지 않습니다.
- 부모로부터 상속 된 스타일이 없습니다.
- 오래되거나 초보적인 브라우저에서는 작동하지 않을 수 있습니다.
- 의사 클래스 및 의사 선택기에 어떻게 대처하는지 확실하지 않지만 괜찮은 것 같습니다.
아마도 언젠가는 이러한 단점을 해결할 것입니다.
긴 버전 2018 년 8 월 12 일
다음은 누군가의 GitHub 페이지 에서 가져온 훨씬 더 포괄적 인 구현입니다
(이 원본 코드 에서 Bugzilla 를 통해 분기 됨 ). Gecko 및 IE 용으로 작성되었지만 Blink에서도 작동한다는 소문이 있습니다.
2017 년 5 월 4 일 : 특이성 계산기에 중요한 버그가 있었지만 이제 수정했습니다. (저는 GitHub 계정이 없기 때문에 저자에게 알릴 수 없습니다.)
2018 년 8 월 12 일 : 최근 Chrome 업데이트는 this독립 변수에 할당 된 메서드에서 개체 범위 ( )를 분리 한 것 같습니다 . 따라서 호출 matcher(selector)이 작동을 멈췄습니다. 로 교체하면 matcher.call(el, selector)문제가 해결되었습니다.
if (typeof window.getMatchedCSSRules !== 'function') {
var ELEMENT_RE = /[\w-]+/g,
ID_RE = /#[\w-]+/g,
CLASS_RE = /\.[\w-]+/g,
ATTR_RE = /\[[^\]]+\]/g,
PSEUDO_CLASSES_RE = /\:(?!not)[\w-]+(\(.*\))?/g,
PSEUDO_ELEMENTS_RE = /\:\:?(after|before|first-letter|first-line|selection)/g;
function toArray(list) {
return [].slice.call(list);
}
function getSheetRules(stylesheet) {
var sheet_media = stylesheet.media && stylesheet.media.mediaText;
if ( stylesheet.disabled ) return [];
if ( sheet_media && sheet_media.length && ! window.matchMedia(sheet_media).matches ) return [];
return toArray(stylesheet.cssRules);
}
function _find(string, re) {
var matches = string.match(re);
return matches ? matches.length : 0;
}
function calculateScore(selector) {
var score = [0,0,0],
parts = selector.split(' '),
part, match;
while (part = parts.shift(), typeof part == 'string') {
match = _find(part, PSEUDO_ELEMENTS_RE);
score[2] += match;
match && (part = part.replace(PSEUDO_ELEMENTS_RE, ''));
match = _find(part, PSEUDO_CLASSES_RE);
score[1] += match;
match && (part = part.replace(PSEUDO_CLASSES_RE, ''));
match = _find(part, ATTR_RE);
score[1] += match;
match && (part = part.replace(ATTR_RE, ''));
match = _find(part, ID_RE);
score[0] += match;
match && (part = part.replace(ID_RE, ''));
match = _find(part, CLASS_RE);
score[1] += match;
match && (part = part.replace(CLASS_RE, ''));
score[2] += _find(part, ELEMENT_RE);
}
return parseInt(score.join(''), 10);
}
function getSpecificityScore(element, selector_text) {
var selectors = selector_text.split(','),
selector, score, result = 0;
while (selector = selectors.shift()) {
if (matchesSelector(element, selector)) {
score = calculateScore(selector);
result = score > result ? score : result;
}
}
return result;
}
function sortBySpecificity(element, rules) {
function compareSpecificity (a, b) {
return getSpecificityScore(element, b.selectorText) - getSpecificityScore(element, a.selectorText);
}
return rules.sort(compareSpecificity);
}
function matchesSelector(el, selector) {
var matcher = el.matchesSelector || el.mozMatchesSelector ||
el.webkitMatchesSelector || el.oMatchesSelector || el.msMatchesSelector;
return matcher.call(el, selector);
}
window.getMatchedCSSRules = function (element /*, pseudo, author_only*/) {
var style_sheets, sheet, sheet_media,
rules, rule,
result = [];
style_sheets = toArray(window.document.styleSheets);
while (sheet = style_sheets.shift()) {
rules = getSheetRules(sheet);
while (rule = rules.shift()) {
if (rule.styleSheet) {
rules = getSheetRules(rule.styleSheet).concat(rules);
continue;
}
else if (rule.media) {
rules = getSheetRules(rule).concat(rules);
continue
}
if (matchesSelector(element, rule.selectorText)) {
result.push(rule);
}
}
}
return sortBySpecificity(element, result);
};
}
버그 수정
= match → += match
return re ? re.length : 0; → return matches ? matches.length : 0;
_matchesSelector(element, selector) → matchesSelector(element, selector)
matcher(selector) → matcher.call(el, selector)