2009-11-12 22 views
0

我需要能夠讓下一個元素/上一個元素用當前元素更改背景顏色。我怎麼做。我工作的元素是TR,表格行和nextSibling,previousSibling不會爲我做這個詭計,不知道爲什麼?懸停下一個/前一個元素

+0

你能告訴我們您所使用的代碼? – jkndrkn

+0

nextSibling和previousSibling應該在TR上工作,您可以發佈一些代碼以獲取更多信息嗎?如果您在TD上設置了背景,則TR將不會正確顯示背景顏色。 –

+0

對不起,我遲到了,我得到它的工作,這是dom的實現讓我,我得做它的工作是不斷尋找next/prev元素,直到我得到一個實際的元素,而不是文本節點,我通過查看節點的類型來做到這一點。 謝謝 – BeNice

回答

1

我認爲我們在這裏即使是「好」的瀏覽器中一個非常惱人的行爲方式有一個情況。

就拿我下面的表格,其中HTML如下所示:

<table border="1"> 
    <thead> 
    <tr id="header"> 
     <th>eng</th> 
     <th>deu</th> 
     <th>spa</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr id="row1"> 
     <td>one</td> 
     <td>eins</td> 
     <td>uno</td> 
    </tr> 
    <tr id="row2"> 
     <td>spoon</td> 
     <td>der Löffel</td> 
     <td>la cucharita</td> 
    </tr> 
    </tbody> 
</table> 

當我在Firefox中打開此起來去到控制檯,並運行下面的片斷,注意nextSibling的行爲方式:

// My input command 
document.getElementById("row1").nextSibling; 
// Output from the console 
<TextNode textContent="\n "> 

我讀過有關這地方,我忘了確切位置(Quirksblog,或者從通話PPK一樣),所以後來我嘗試了以下內容:

// my input command 
document.getElementById("row1").nextSibling.nextSibling; 
// output from the console 
<tr id="row2"> 

這是我們美妙的標準兼容瀏覽器(IMHO)絕對錯誤的時刻之一。

爲了測試,我決定單行我的表的HTML,所以(希望它顯示了所有在同一行):

<table border="1"><thead><tr id="header"><th>eng</th><th>deu</th><th>spa</th></tr></thead><tbody><tr id="row1"><td>one</td><td>eins</td><td>uno</td></tr><tr id="row2"><td>spoon</td><td>der Löffel</td><td>la cucharita</td></tr></tbody></table> 

並再次運行我的測試:

// Hmmm, does nextSibling work _as expected_ now? 
document.getElementById("row1").nextSibling; 
// yep 
<tr id="row2"> 

Benice,你的想法是正確的,但你在瀏覽器部分的實施監督中偏離了我的想法。我建議您非常小心使用跨瀏覽器的HTML DOM關係。他們大多數工作如預期,但有時他們不。

啊,發現這個畢竟一篇文章:https://developer.mozilla.org/en/Whitespace_in_the_DOM

+0

一個跟進,當我說Benice的想法是正確的時候,我應該說我相信我所做的事情是正確的,因爲我沒有看到他的代碼。 – jeremyosborne

0

使用jQuery,您可以應用hover()函數,並將具有適當背景顏色的類設置爲下一行和前一行。走出一行會從這些行中刪除高亮。可以肯定的是,在將其應用於任何行之前,您需要重置整個表上的高亮類。

$('tr').hover(
    function() { 
     var $this = $(this); 
     $this.closest('table').find('tr').removeClass('highlight'); 
     $this.next('tr').addClass('highlight'); 
     $this.prev('tr').addClass('highlight'); 
     $this.addClass('highlight'); 
    }, 
    function() { 
     var $this = $(this); 
     $this.next('tr').removeClass('highlight'); 
     $this.prev('tr').removeClass('highlight'); 
     $this.removeClass('highlight'); 
    } 
}); 

這取決於這個片段CSS

.highlight { 
    background-color: #ff8; /* or whatever color you choose */ 
}