繁体   English   中英

悬停时更改表格行的背景颜色

[英]Changing background color of table row on hover

这是我在这里的第一篇文章,对不起,如果我的文章有点混乱。

我正在使用HTML5,CSS和Javascript进行作业。 每当用户将鼠标悬停在该行上时,我都尝试使用javascript更改表行背景的颜色。 但是,我遇到了两个问题。

这是包含完整代码的JSFiddle链接:

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

第一个问题似乎与这段代码有关。 此代码交替显示行颜色。 删除后,每当我将鼠标悬停在一行上时,表格行的背景颜色就会发生变化。 但是,如果我将此代码包含在javascript文件中,则行背景色不会更改。

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';

其次,尽管代码在JSFiddle上运行,但即使从JavaScript文件中删除了上面的代码,运行时它也似乎无法在我的Web浏览器中运行。

编辑

这是负责在悬停时更改表格行背景颜色的Javascript代码

$(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");
    });
});

以及我与上述javascript代码结合使用的CSS代码

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;
}

这里的问题是CSS特异性。 向TR添加类将取消样式表中的CSS。 而不是直接应用颜色,而是添加一个类(偶数/奇数)。

你甚至不需要一个类,简单的css规则就可以做斑马条纹。

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

而且您说您需要JavaScript进行悬停,实际上,您需要Java来支持旧的IE。 当今的浏览器无需JavaScript就可以做到这一点

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

您唯一需要做的就是添加一个用于单击行的类

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

和JavaScript

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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