首先,你必须在JavaScript中获得表中所有按钮的引用(你可以获得 document.getElementsByTagName 获取所有按钮, getElementsByName 如果你给所有按钮命名相同(没有其他元素),或 getElementsByClassName 如果你给所有的按钮都是同一个类(没有其他元素) .
// get all of the buttons in the table (I gave them all a class of tablebutton
var buttons = document.getElementsByClassName("tablebutton");
接下来,您必须循环按钮数组并添加两个事件侦听器,一个用于 mouseover (悬停)事件,另一个用于 mouseout (悬停)事件 .
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.addEventListener("mouseover", highlightRow, false);
button.addEventListener("mouseout", unHighlightRow, false);
}
在这些事件侦听器中,您必须遍历DOM树,从按钮到表行,然后将行的背景颜色设置为突出显示的颜色或“”以删除颜色 .
function highlightRow ()
{
var row = this.parentNode.parentNode;
row.style.backgroundColor = "red";
}
function unHighlightRow ()
{
var row = this.parentNode.parentNode;
row.style.backgroundColor = "";
}
(您也可以使用匿名函数,而不是使用名称定义函数...
button.addEventListener("mouseover", function () {
...your code here
}, false);
button.addEventListener("mouseout", function () {
...your code here
}, false);