如何在单击并悬停时更改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');
});
});
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
相关文章:
- 如何在td元素中添加监听器
- 使用querySelector()获取最后一个td元素
- 使用 Jquery 选择一个 td 元素
- 将图像附加到没有 id 或值的 td 元素
- td元素中带有传递参数的Javascript函数
- 事件点击不在td元素中的多个锚点标记上处理同一个类
- 浏览器中的javascript和td元素事件属性
- 正在获取循环中td元素的tr id
- 正在查找表行中的td元素位置
- 无法动态设置表的 td 元素的值
- td 元素上的 OnClick 函数返回第一列值和标头值
- JQuery 正在添加一个类,但不会从多个 td 元素中删除它
- 使用 javascript 动态添加到 td 元素的 Onclick 不起作用
- 在 jQuery 中更改 TD 元素
- Javascript.使用鼠标悬停事件更改数组中 td 元素的背景颜色
- 使用 JavaScript 移动 html td 元素
- 如何将每个 td 元素的高度设置为其宽度
- 单击时获取TR的所有TD元素
- 使用 jquery find('.classname') 无法定位 TD 元素
- 无法在表的悬停td元素上显示Popover