getComputedStyle の結果から margin プロパティの値を取得できません 質問する

getComputedStyle の結果から margin プロパティの値を取得できません 質問する

の結果にはgetComputedStyle「margin」というプロパティが含まれますが、""Mozilla Firefox または Apple Safari ではこのプロパティは常に空の文字列 ( ) になります。ただし、Internet Explorer (および Google Chrome) では、margin プロパティに期待される値が含まれます (IE 6 でも)。getPropertyValue("margin")返されたオブジェクトの メソッドを使用すると、同じ結果が返されます。

Firefox と Safari でマージンの計算値を取得するにはどうすればよいですか?

var el = document.body.appendChild(document.createElement('div'));
el.style.margin = '2px';
console.log(getComputedStyle(el, null).margin === ""); // false in IE and Chrome
console.log(getComputedStyle(el, null).getPropertyValue("margin") === ""); // same

ベストアンサー1

関数getComputedStyle()ショートハンドプロパティの値を評価しないmargin( 、などpadding) の場合、ロングハンド プロパティ ( margin-top、、margin-bottomなどpadding-top) のみを返します。ショートハンド プロパティの場合は、空の文字列のみを返します。

var el = document.body.appendChild(document.createElement('div'));
el.style.margin = '2px';
var computed = getComputedStyle(el);

var longhands = ['margin-top', 'margin-bottom', 'margin-left', 'margin-right'];
longhands.forEach(function(e) { console.log(e + ': ' + computed.getPropertyValue(e)) });

さらに、以下もご覧くださいこのリンククロスブラウザソリューションでは、currentStyleインターネットエクスプローラを使用します

おすすめ記事