Javascript addEventListener - 使用来创建鼠标悬停效果? [英] Javascript addEventListener - using to create a mouseover effect?
问题描述
var item = document.getElementById(button);
item.addEventListener(mouseover,func,false);
函数func()
{
var item = document.getElementById(button);
item.setAttribute(style,background-color:blue)
}
然而,当我悬停时,这只将项目的颜色设置为蓝色,但是在我将鼠标移开后不会将其重置为白色。我该如何纠正? (btw,mouseenter和mouseleave不适用于这个看似)。
您将需要设置一个类似的事件来处理 mouseout
。在mouseout事件功能中,您可以将颜色更改回原始颜色。
var item = document.getElementById(button);
item.addEventListener(mouseover,func,false);
item.addEventListener(mouseout,func1,false);
函数func()
{//不需要,因为项目已经是全局的,
//我假设这里只是因为它是示例代码?
// var item = document.getElementById(button);
item.setAttribute(style,background-color:blue;)
}
函数func1()
{
item.setAttribute (style,background-color:green)
}
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).
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).
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.
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;")
}
这篇关于Javascript addEventListener - 使用来创建鼠标悬停效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!