简体   繁体   中英

Changing background color of table row on hover

This is my first post here, so sorry if my post is a little confusing.

I'm working on an assignment which uses HTML5, CSS, and Javascript. I'm trying to use javascript to change the color of a table row's background whenever a user hovers over that row. However, i've run into two issues.

Here's a link to the JSFiddle containing the entire code:

http://jsfiddle.net/bguqp/8/

The first issue seems to be with this segment of code. This code alternates the rows colors. When removed, the table row's background color changes as it should whenever I hover over a row. However, if I include this code in the javascript file, the row background color does not change.

var tblrows = document.getElementsByTagName('tr');

for(i=0;i<tblrows.length;i++){
    if(i%2==0) tblrows[i].style.backgroundColor = '#0000FF';
    else tblrows[i].style.backgroundColor = '#C0C0C0';

Second, while the code is working on JSFiddle, it does not seem to be working in my web browser when run, even with the code above removed from the javascript file.

EDIT

Here is the Javascript code responsible for changing the table row background color on hover

$(document).ready(function(){
    $("table.stripe_table tr:odd").addClass("alternate");

    $("table.stripe_table tr").mouseover(function(){
        $(this).addClass("tr_onmouseover");
    });
    $("table.stripe_table tr").mouseout(function(){
        $(this).removeClass("tr_onmouseover");
    });
    $("table.stripe_table tr").click(function(){
        $(this).toggleClass("tr_onmouseclick");
    });
});

and the CSS code i'm using in conjunction with the above javascript code

table.stripe_table tr.alternate{
    background-color: #CCC;
}
table.stripe_table tr.tr_onmouseover{
    background-color: #FC0
}
table.stripe_table tr.tr_onmouseclick{
    background-color: #F00;
}

The problem here is CSS specificity. Adding a class to the TR will cancel out the CSS in the stylesheet. Instead of applying colors directly, add a class (even/odd).

Heck you do not even need a class, simple css rule can do zebra stripes.

tbody tr:nth-child(odd) {
   background-color: #C0C0C0;
}

And you say you need JavaScript for hover, in reality you needed it for old IE support. Modern day browsers can do it without JavaScript

table.stripe_table tr:hover{
    background-color: #FC0
}

only thing you would need to do is add a class for clicking on a row

table.stripe_table tr.selected{
    background-color: #F00
}

and the JavaScript

$(document).on("click","tbody tr", function () {
   $(this).toggleClass("selected");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM