如何在JavaScript中编写hoverHandler,以便在悬停时更改元素的颜色?
这是我的代码,我还有一个CSS,当id悬停时设置颜色 问题是:如何在JavaScript中编写hoverHandler,以便在悬停时更改元素的颜色?,javascript,events,handler,web,Javascript,Events,Handler,Web,这是我的代码,我还有一个CSS,当id悬停时设置颜色 问题是: 1) 当我悬停时,当我离开元素时,颜色不会重置回以前的颜色难道你不能用Css来解决这个问题吗 差不多 function hoverHandler(e) { if(event.target.getAttribute("id") != "hovering") { event.target.setAttribute("id", "hovering"); } } 其中element是类名请尝试添加,并确保您也检查了onmouseo
1) 当我悬停时,当我离开元素时,颜色不会重置回以前的颜色难道你不能用Css来解决这个问题吗 差不多
function hoverHandler(e)
{
if(event.target.getAttribute("id") != "hovering")
{
event.target.setAttribute("id", "hovering");
}
}
其中element是类名请尝试添加,并确保您也检查了
onmouseout
.element:hover
{
background-color: #FF0000;
}
是的,但我的作业中不允许这样做,我必须使用处理程序。你需要使用这个函数还是任何javascript解决方案?
<script>
function hoverHandler(e)
{
if(e.id=="red") // hovering
{
e.id="blue";
}else {
e.id="red";
}
}
</script>
<span onmouseover="hoverHandler(this)" onmouseout="hoverHandler(this)">test</span>
<style>#startStyle {color:lime} #red {color:red}#blue{color:blue}</style>
<span onmouseover="this.id='red'" onmouseout="this.id=''">test</span>
<span onmouseover="this.id='red'" onmouseout="this.id='startStyle'">test</span>