2016-11-28 4 views
1

を割り当てるときに、なぜ(!のみ)エッジが文句を言うんはJS strictモード:スタイルプロパティ

次のコードを考えてみましょう
"use strict"; 
var el = document.createElement('div'); 
el.className = 'bluebox'; 
el.style = 'background:blue; width:100px; height: 100px'; 
document.getElementsByTagName('body')[0].appendChild(el) 

のFirefoxとChromeは、Element

<div class="yolo" style="background: blue none repeat scroll 0% 0%; width: 100px; height: 100px;"> 

を作成しません。しかしエッジがスローされますエラー:

Assignment to read-only properties is not allowed in strict mode 

何が起こっているのですか?スタイル属性は実際には読み取り専用で、FFとChromeは正しく動作しませんか、Edgeに厳密モードの別のコンセプトがありますか?ここで尋ねることなく、どうやってこれを見つけることができますか?

+2

el.style.background = '' の方法だろう。他のブラウザが不平を言っていなくても、動作しません。エッジは実際にこれで正しいです。 – Lain

答えて

1

What is happening here?

あなたは間違ってプロパティコレクションを割り当てようとしました。

Is the style attribute actually read-only and FF and Chrome behave incorrectly or do has Edge another concept of strict mode or...?

いいえ、属性(setAttribute( 'style'、 ''))を設定すると、すべてが機能していました。しかし、プロパティはオブジェクトです - コレクションと異なる動作します。だから、今回はEdgeが実際には正解です。

How could I possibly find this out without asking here?

あなたが読んで、グーグルができます

https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

Exmaples:

elt.style.cssText = "color: blue"; // Multiple style properties 

elt.setAttribute("style", "color: blue"); // Multiple style properties 

elt.style.color = "blue"; // Directly 

var st = elt.style; 
st.color = "blue"; // Indirectly 
+0

あなたのリンクは、IEがOPの質問の構文が気に入らないことを明確には伝えていません_Stylesは、スタイルプロパティ(elt.style = "color:blue;"のように)に直接文字列を割り当てることで設定できます。 .style.cssText = "color:blue;"ただし、読み取り専用のCSSStyleDeclarationオブジェクトが返されます。スタイル・プロパティーを使用してもスタイル属性にすでに設定されている可能性のある他のCSSプロパティーは上書きされないため、単一のステートメントで完全なスタイルを設定したい場合は除きます。 – mplungjan

+0

@James Thrope:感謝しました:) – Lain

+0

@mplungjan:それは厳密に正しいと読んでいます。しかし、文書は通常、「物事」が何をしているのか、物事が何をしていないのかを伝えるものではない。 – Lain

関連する問題