C..*_*C.. 5 html javascript onmouseover javascript-events
当用户的鼠标超过第一个提到的td时,我需要将td背景更改为灰色并在另一个td中更改文本.
到目前为止我做到了这一点:
<td onMouseOver="this.style.background='#f1f1f1'" onMouseOut="this.style.background='white'">
Run Code Online (Sandbox Code Playgroud)
但这只会改变第一个td的背景,而不会改变第二个td中的文本
有什么想法吗?
看看这个:
function highlightNext(element, color) {
var next = element;
do { // find next td node
next = next.nextSibling;
}
while (next && !('nodeName' in next && next.nodeName === 'TD'));
if (next) {
next.style.color = color;
}
}
function highlightBG(element, color) {
element.style.backgroundColor = color;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<td onMouseOver="highlightBG(this, 'red');highlightNext(this, 'red')"
onMouseOut="highlightBG(this, 'white');highlightNext(this, 'black')" >
Run Code Online (Sandbox Code Playgroud)
请注意,在HTML中添加事件处理程序不被视为良好做法.
根据你想要支持的浏览器(它肯定不能在IE6中运行),你真的应该考虑即使JS被关闭也能工作的CSS方法.代码少得多,将此行为添加到多个元素会更容易:
td:hover {
background-color: red;
}
td:hover + td {
color: red;
}
Run Code Online (Sandbox Code Playgroud)