2

悬停时以及单击时,我需要更改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标签。

4

4 回答 4

4

我稍微修改了上面的答案。尝试用更多的 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');
    });
});

小提琴演示

于 2013-07-20T11:55:10.680 回答
1

它应该像'tr td',

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

小提琴演示

于 2013-07-20T11:32:46.297 回答
0

只需要css:

td:hover {
    background-color: red;
}

或JavaScript:

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

还有..如何同时悬停和单击一个元素?面向对象

于 2013-07-20T12:01:08.230 回答
0

尝试绑定事件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');    
    });       
});

尝试这个

于 2013-07-20T11:57:50.140 回答