如何在单击并悬停时更改td元素背景

How do I change a td element background on click and hover?

本文关键字:td 元素 背景 悬停 单击      更新时间:2023-09-26

悬停时以及单击时,我需要更改表中td元素的背景。

我的代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>Table Highlighting</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
    $('table').on('mouseover', 'tr', function(){
        $(this).css({
            'background-color': '#DBE9FF'
        });
    }).on('mouseout', 'tr', function(){
        $(this).css({
            'background-color': '#FFFFFF'
        });
    }).on('click', 'td', function(){
        $(this).parent().children().css({
            'background-color': '#FFFFFF'
        });
        $(this).css({
            'background-color': '#7DAFFF'
        });
    });
});
</script>
<style>
table
{
    border-collapse: collapse;
}
td
{
    padding: 5px;
    border: 1px solid #666666;
    cursor: pointer;
}
</style>
</head>
<body>
<table>
    <tr>
        <td>
        Row 1 Col 1
        </td>
        <td>
        Row 1 Col 2
        </td>
        <td>
        Row 1 Col 3
        </td>
        <td>
        Row 1 Col 4
        </td>
        <td>
        Row 1 Col 5
        </td>
    </tr>
 </table>
</body>
</html>

它工作得很好,因为当我点击td时,背景会发生变化,但悬停应用于tr,我只需要td背景在悬停时发生变化,并点击特定的td,而不是其他td标签。

我稍微修改了上面的答案。试着用更多的CSS来处理事情。使用javascript/jquery的悬停伪即时,如果你能帮助它使用一个类为你的td.添加样式

CSS

tr td:hover
{
    background-color: #DBE9FF;
}
.active
{
  background-color: #7DAFFF;
}

Jquery

$(function(){
    $('table').on('click', 'td', function(){
        // Remove all active class from all td 
        $(this).parent().children().removeClass('active');
        // Add active class to current td target 
        $(this).addClass('active');
    });
});

Fiddle演示

它应该像"tr td",

$('table').on('mouseover', 'tr td', function(){
        $(this).css({
            'background-color': '#DBE9FF'
        });
    }).on('mouseout', 'tr td', function(){
        $(this).css({
            'background-color': '#FFFFFF'
        });

Fiddle演示

尝试绑定table tr td上的事件--

$(function(){
    $('table tr td').click(function(){
      $(this).css('background-color','#DBBBBF');    
    })
    $('table tr td').mouseout(function () {
      $(this).css('background-color','#FFFFFF');    
    });
    $('table tr td').mouseover(function () {
      $(this).css('background-color','#DBE9FF');    
    });       
});

试试这个

只需要css:

td:hover {
    background-color: red;
}

或者javascript:

<td onmouseover="this.style.background-color = 'red';">

而且。。如何将鼠标悬停并同时单击一个元素?O.O