jQuery mouseover not working as intended

喜夏-厌秋 提交于 2019-12-08 06:31:43

问题


This is the html I have:

<div id="social">
    <a href="#" class="twitter"><span class="text">Twitter</span></a>
</div>

What I intend to do is initially hide the span.text and when I hover over the image in the background of the div. This is my css

#social a {
    display:inline-block;
    overflow:hidden;
    padding:4px 0 0 28px;
/* left padding is for the bg image to be visible*/
}
#social a span {
    display:none;
}
#social .twitter {
    background:url(../images/social/twitter.png) no-repeat left top;
}
#social .twitter:hover {
    background:url(../images/social/twitter_hover.png) no-repeat left top;
}

And this is my js:

$("#social a.twitter").mouseover(function(){
  $("span",this).show("slow");
}).mouseout(function(){
  $("span",this).hide("slow");
});

But what happens is when I hover over the image it keeps on showing and hiding the text.. Where am I going wrong?


回答1:


you have a very common problem, when the span shows, the mouse its not any more over the a, so the mouseout event gets called.

to fix this use mouseenter and mouseleave events

$("#social a.twitter").mouseenter(function(){
  $("span",this).show("slow");
}).mouseleave(function(){
  $("span",this).hide("slow");
});​

fiddle for you :D

and, in css the comments are with /* */ and not with //




回答2:


In your CSS:

// left padding is for the bg image to be visible

// is not a valid symbol for comments.

They have to be wrapped in /* */ like:

/* left padding is for the bg image to be visible */



回答3:


You don't need to (and shouldn't) use javascript for this effect. You can do it with CSS, which is cleaner and more semantic :). Example:

​a.twitter {
    display: block;
    width: 300px;
    height: 300px;
    background: url('http://www.simplyzesty.com/wp-content/uploads/2012/01/twitter_newbird_boxed_whiteonblue2.png');
}

a.twitter span {
    opacity: 0;
    -webkit-transition: opacity 0.2s;
    -moz-transition: opacity 0.2s;
    -o-transition: opacity 0.2s;
    transition: opacity 0.2s;
}

a.twitter:hover span {
    opacity: 1;
}

jsFiddle: http://jsfiddle.net/Ut4Gx/




回答4:


Try using mouseleave. Re mouseout:

This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the Inner element in this example, a mouseout event will be sent to that, then trickle up to Outer. This can trigger the bound mouseout handler at inopportune times. See the discussion for .mouseleave() for a useful alternative.



来源:https://stackoverflow.com/questions/11130734/jquery-mouseover-not-working-as-intended

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!