繁体   English   中英

如何在点击和悬停时更改td元素背景?

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

悬停时以及单击时,我需要更改表中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');
    });
});

小提琴演示

应该像“ tr td”

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

小提琴演示

尝试在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';">

以及..如何同时悬停和单击元素? OO

暂无
暂无

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

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