6

当用户的鼠标经过第一个提到的 td 时,我需要将 td 背景更改为灰色并在另一个 td 中显示文本。

到目前为止,我已经这样做了:

<td onMouseOver="this.style.background='#f1f1f1'" onMouseOut="this.style.background='white'">

但这只会改变第一个 td 的背景,不会改变第二个 td 中的文本。

请问有什么想法吗?

4

2 回答 2

10

看看这个:

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;
}

HTML:

<td onMouseOver="highlightBG(this, 'red');highlightNext(this, 'red')" 
    onMouseOut="highlightBG(this, 'white');highlightNext(this, 'black')" >

演示

请注意,在 HTML 中添加事件处理程序并不是一种好的做法。


根据您想要支持的浏览器(它肯定不会在 IE6 中工作),您真的应该考虑 CSS 方法,即使关闭 JS 也可以工作。代码少得多,并且更容易将此行为添加到多个元素:

td:hover {
    background-color: red;          
}

td:hover + td {
    color: red;   
}

演示

于 2011-02-04T12:31:17.647 回答
0

您应该给其他 td 一个 id 并从您的 onmouseover 事件处理程序访问它。也许你应该把那个 onmouseover 代码放到它自己的函数中,然后从 onmouseover 中调用它。

于 2011-02-04T12:49:08.647 回答