0

この要素の背景色を変更することができます:

<div onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">
</div>

しかし、私は最初の子の色を変更したいと思います。これは次のように機能すると想定しました。

<div onmouseover="this.firstChild.style.backgroundColor='blue'" onmouseout="this.firstChild.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">

  <div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>

</div>

しかし、それは機能しません。なにが問題ですか?firstChildのスタイルを変更するにはどうすればよいですか?

PS:後で、子にdisplay = blockを使用し、noneと他のいくつかのプロパティ(スタイルだけでなく)を使用したいと思います。色はテスト用でした。

4

2 に答える 2

4

「システム」で述べたように、要素ノードではなくテキストノードをターゲットにしています。children[0]の代わりに使用してみてくださいfirstChild

jFiddleはこちら

于 2013-02-19T21:07:44.513 に答える
3

を使用する必要があり.firstElementChildます。そうでない場合は、書式設定の空白を削除する必要があります。その空白はテキストノードになります。これは.firstChildです。

この.firstElementChildプロパティは一部の古いブラウザではサポートされていないため、それらをサポートしている場合は、関数を使用してシムする必要があります。


<div onmouseover="changeColor(this, 'blue')" onmouseout="changeColor(this, 'red')" style="background-color:green; width:100px; height:40px;">

  <div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>

</div>

function changeColor(el, color) {
    firstElemChild(el).style.backgroundColor=color;
}
function firstElemChild(el) {
    if (el.firstElementChild)
        return el.firstElementChild;

    el = el.firstChild

    while (el && el.nodeType !== 1)
        el = el.nextSibling;

    return el;
}
于 2013-02-19T21:04:02.457 に答える