MouseOver事件更改TD背景和文本 [英] MouseOver event to change TD background and text

查看:110
本文介绍了MouseOver事件更改TD背景和文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to change the td background to grey and text in another td when the user's mouse goes over the first mentioned td.

到目前为止我已经完成了这个:

I have done this so far:

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

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

but this only changes the background of the first td and does not change the text in the second 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;
}

HTML:

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

DEMO

请注意,在HTML中添加事件处理程序不被视为良好做法。

Note that adding the event handler in the HTML is not considered to be good practice.

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

Depending on which browser you want to support (it definitely won't work in IE6), you really should consider the CSS approach which will work even if JS is turned off. Is much less code and it will be easier to add this behaviour to multiple elements:

td:hover {
    background-color: red;          
}

td:hover + td {
    color: red;   
}

DEMO

这篇关于MouseOver事件更改TD背景和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆