Javascript 更改 TD 背景和文本的 MouseOver 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4897737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MouseOver event to change TD background and text
提问by C..
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.
当用户的鼠标移过第一个提到的 td 时,我需要将 td 背景更改为灰色,并将另一个 td 中的文本更改为灰色。
I have done this so far:
到目前为止,我已经这样做了:
<td onMouseOver="this.style.background='#f1f1f1'" onMouseOut="this.style.background='white'">
but this only changes the background of the first td and does not change the text in the second td
但这只会改变第一个 td 的背景,不会改变第二个 td 中的文本
any ideas please?
请问有什么想法吗?
回答by Felix Kling
Have a look at this:
看看这个:
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:
HTML:
<td onMouseOver="highlightBG(this, 'red');highlightNext(this, 'red')"
onMouseOut="highlightBG(this, 'white');highlightNext(this, 'black')" >
Note that adding the event handler in the HTML is not considered to be good practice.
请注意,在 HTML 中添加事件处理程序不被认为是一种好的做法。
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:
根据您想要支持的浏览器(它肯定不会在 IE6 中工作),您真的应该考虑 CSS 方法,即使关闭 JS 也能工作。代码少得多,将这种行为添加到多个元素会更容易:
td:hover {
background-color: red;
}
td:hover + td {
color: red;
}
回答by nokul
You should give that other td an id and access it from your onmouseover event handler. Maybe you should put that onmouseover code into its own function and call it from the onmouseover.
您应该给其他 td 一个 id 并从您的 onmouseover 事件处理程序访问它。也许你应该把那个 onmouseover 代码放到它自己的函数中并从 onmouseover 调用它。