Hover next / previous element
I need to be able to have the next element / previous element to change the background color with the current element. How do I do that. The element that I am working is TR, table row, and nextSibling, previousSibling doesn't do the trick for me, don't开发者_JAVA百科 know why ?
I think we have a case here of even the "good" browsers behaving in an extremely annoying way.
Take for example my following table, where the HTML looks like the following:
<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>
When I open this up in Firefox and go to the console and run the following snippets, notice the how nextSibling behaves:
// My input command
document.getElementById("row1").nextSibling;
// Output from the console
<TextNode textContent="\n ">
I've read about this somewhere, and I forget exactly where (Quirksblog, or perhaps from a talk PPK did), so then I tried the following:
// my input command
document.getElementById("row1").nextSibling.nextSibling;
// output from the console
<tr id="row2">
This is one of those moments where our wonderful standards compliant browsers do it (IMHO) absolutely wrong.
To test, I decide to single line the HTML of my table, hence (hopefully it shows up all on one line):
<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>
And run my test again:
// Hmmm, does nextSibling work _as expected_ now?
document.getElementById("row1").nextSibling;
// yep
<tr id="row2">
Benice, your idea was correct, but you got bit by what I like to think of as an implementation oversight on the browser's part. I recommend being very careful with HTML DOM relationships cross-browser. Most of them work as expected, but sometimes they don't.
Ahh, found an article about this after all: https://developer.mozilla.org/en/Whitespace_in_the_DOM
Using jQuery you could apply the hover() function and set a class which has the appropriate background color to the next and previous rows. Going out of a row would remove the highlight from those rows. To be sure, you'd reset the highlight class on the entire table before applying it to any rows.
$('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');
}
});
This depends on this snippet of CSS
.highlight {
background-color: #ff8; /* or whatever color you choose */
}
精彩评论