4

<style>特定の CSS プロパティがタグ内で定義されているかどうかを確認する必要があるスクリプトを作成しています。

<style type="text/css">
#bar {width: 200px;}
</style>
<div id="foo" style="width: 200px;">foo</div>
<div id="bar">bar</div>
// 200px
console.log(document.getElementById("foo").style.width);

// an empty string
console.log(document.getElementById("bar").style.width);

if(property_width_defined_in_style_tag) {
    // ...
}

これは可能ですか?

私はところで取得しようとしていませんgetComputedStyle(ele).width

4

2 に答える 2

6

これがあなたが望むものかどうかはわかりませんが、要素インスタンスがあった最初の疑似コードに最も近い動作をします。

var proto = Element.prototype;
var slice = Function.call.bind(Array.prototype.slice);
var matches = Function.call.bind(proto.matchesSelector || 
                proto.mozMatchesSelector || proto.webkitMatchesSelector ||
                proto.msMatchesSelector || proto.oMatchesSelector);

// Returns true if a DOM Element matches a cssRule
var elementMatchCSSRule = function(element, cssRule) {
  return matches(element, cssRule.selectorText);
};

// Returns true if a property is defined in a cssRule
var propertyInCSSRule = function(prop, cssRule) {
  return prop in cssRule.style && cssRule.style[prop] !== "";
};

// Here we get the cssRules across all the stylesheets in one array
var cssRules = slice(document.styleSheets).reduce(function(rules, styleSheet) {
  return rules.concat(slice(styleSheet.cssRules));
}, []);

// get a reference to an element, then...
var bar = document.getElementById("bar");

// get only the css rules that matches that element
var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, bar));

// check if the property "width" is in one of those rules
hasWidth = elementRules.some(propertyInCSSRule.bind(null, "width"));

このコードのすべてを目的のために再利用することも、一部だけを再利用することもできると思います。意図的にモジュール化されています。たとえば、すべてのcssRulesフラット化または. ES5関数とmatchesSelectorを使用しているため、古いブラウザではシムなしでは機能しません。さらに、優先度などでフィルタリングすることもできます。たとえば、インライン スタイルのものよりも優先度が低いすべてのプロパティを削除できます。elementRulesfor

于 2013-03-27T20:45:38.270 に答える
5

javascript でstyleSheetsを完全に調べることができます。

document.styleSheets配列から始めます。値は、ドキュメントで使用されるさまざまなスタイル要素または CSS ファイルです。

于 2013-03-27T19:13:17.697 に答える