使用 jquery 在悬停时向表格行添加背景颜色和边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/688222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:35:17  来源:igfitidea点击:

Add background color and border to table row on hover using jquery

jquerycss

提问by Chris Conway

Does anyone know of a way to add a border to a table row with a different background color when the mouse hovers over the row?

有没有人知道当鼠标悬停在行上时向具有不同背景颜色的表格行添加边框的方法?

I've been able to change the background color of the row with this:

我已经能够通过以下方式更改行的背景颜色:

$(document).ready(function() {
   $(function() {
        $('.actionRow').hover(function() {
            $(this).css('background-color', '#FFFF99');
        },
        function() {
            $(this).css('background-color', '#FFFFFF');
        });
    });
});

But I'm unable to add a border color. I realize borders can't be directly applied to a table row tag, but I'm hoping someone know some jQuery voodoo magic that can find the table cells within the selected row and apply some styles to those to create the border.

但我无法添加边框颜色。我意识到边框不能直接应用于表格行标记,但我希望有人知道一些 jQuery 巫术魔法,可以找到所选行中的表格单元格并将一些样式应用于这些单元格以创建边框。

Thanks!

谢谢!

回答by tom

   $(function() {
        $('tr').hover(function() {
            $(this).css('background-color', '#FFFF99');
            $(this).contents('td').css({'border': '1px solid red', 'border-left': 'none', 'border-right': 'none'});
            $(this).contents('td:first').css('border-left', '1px solid red');
            $(this).contents('td:last').css('border-right', '1px solid red');
        },
        function() {
            $(this).css('background-color', '#FFFFFF');
            $(this).contents('td').css('border', 'none');
        });
    });

回答by Mister Lucky

Your best bet would be to addClass and removeClass on the row. Then in your stylesheet:

您最好的选择是在行上添加类和删除类。然后在您的样式表中:

.actionRow-hovered td { border-color: whatever; }

So you will actually be manipulating each of the td border colors instead. A pain, but works well enough when you get the hang of it.

因此,您实际上将操纵每个 td 边框颜色。一种痛苦,但当你掌握它时效果很好。

回答by Vipin Kumar R. Jaiswar

$('table.tblMenuTabls tr').hover(function(){
        $(this).toggleClass('tblOverRow');
        },function(){
            $(this).toggleClass('tblOverRow')}
    ).css({cursor: 'hand'});

Where tblMenuTablsis the table class name and tblOverRowis CSS class with hover definition.

tblMenuTabls表类名在哪里,tblOverRow是带有悬停定义的 CSS 类。