Javascript addEventListener - 用于创建鼠标悬停效果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8318591/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:33:17  来源:igfitidea点击:

Javascript addEventListener - using to create a mouseover effect?

javascriptdom

提问by antonpug

I have a div with an id of "button". I am trying to change its background to become blue when I hover (without using the CSS hover selector).

我有一个 ID 为“按钮”的 div。我试图在悬停时将其背景更改为蓝色(不使用 CSS 悬停选择器)。

var item = document.getElementById("button");
item.addEventListener("mouseover", func, false);

function func()
{  
   var item = document.getElementById("button");
   item.setAttribute("style", "background-color:blue;")
}

This, however, only sets the color of the item to blue when I hover, but does not reset it to white after I move mouse away. How can I correct this? (btw, mouseenter and mouseleave do not work with this seemingly).

但是,这只会在我悬停时将项目的颜色设置为蓝色,但在我将鼠标移开后不会将其重置为白色。我该如何纠正?(顺便说一句,mouseenter 和 mouseleave 似乎不适用于此)。

回答by AndrewR

You will need to setup a similar event to handle mouseout. Inside the mouseout event function, you can change the color back to the original color.

您需要设置一个类似的事件来处理mouseout. 在 mouseout 事件函数中,您可以将颜色改回原来的颜色。

var item = document.getElementById("button");
item.addEventListener("mouseover", func, false);
item.addEventListener("mouseout", func1, false);

function func()
{  // not needed since item is already global, 
   // I am assuming this is here just because it's sample code?
   // var item = document.getElementById("button"); 
   item.setAttribute("style", "background-color:blue;")
}

function func1()
{  
   item.setAttribute("style", "background-color:green;")
}

回答by nnnnnn

Have you tried mouseout?

你有没有试过mouseout

(Unfortunately the event "mouseover" was poorly named - it would've been better if it had been called "mousein" so that it was more obviously and intuitively the opposite of "mouseout". But that's just one of many inconsistent event things.)

(不幸的是,“鼠标悬停”事件的名称很糟糕——如果将它称为“鼠标移开”会更好,这样它在更明显和直观上与“鼠标移开”相反。但这只是许多不一致的事件之一。 )

I think mouseenter and mouseleave are IE things that other browsers may not support - though I think jQuery supports those events too.

我认为 mouseenter 和 mouseleave 是其他浏览器可能不支持的 IE 东西——尽管我认为 jQuery 也支持这些事件。