Jquery fadeOut on hover

青春壹個敷衍的年華 提交于 2019-12-24 03:45:17

问题


I need a bit of help with jquery to get a fadeOut effect happening, here is my code:

http://jsfiddle.net/PPpnT/25/

When you hover over the image the image needs to fade out and show the red underneath, when you mouse off the image should fade back. I think the code may need a stop function - just having a hard time writing it.

All suggestions welcome!


回答1:


In your specific jsFiddle, use this:

$('#show').hover(function() {
    $(this).stop(true).fadeTo("slow", 0);
}, function() {
    $(this).stop(true).fadeTo("slow", 1);
});​

You can see it work here: http://jsfiddle.net/jfriend00/BJwn7/.

They key here is you can't use .fadeOut() and .fadeIn() because when they are done, they set display: none which causes the element to be hidden and that messes up the .hover() function. So, instead just fade the opacity to 0 (but the hover stays in effect) and then when the hover leaves, fade back to opacity of 1.

I also had to remove the opacity CSS for the red block from your jsFiddle because you want it to be visible when you fade out the image so you can just leave it visible behind the image.

If you only wanted the effect in browser that support CSS3 transitions (no version of IE yet), then you could also do this without jQuery/javascript and just use CSS3 transitions. But for something as simple as this, when you already have jQuery, it's pretty easy to just use jQuery fades and get cross browser support.




回答2:


$('#show').hover(
  function () {
    $(this).fadeOut("slow");
  }, 
  function () {
    $(this).fadeIn("slow");
  }
);



回答3:


You started with CSS transitions, so here's an example that uses this:

  • http://jsfiddle.net/PPpnT/33/

I use Firefox, so the example was updated for Firefox only, but the others should be symmetrical.

Read more about this here:

  • http://net.tutsplus.com/tutorials/html-css-techniques/css-fundametals-css-3-transitions/

Credits:

  • CSS Webkit Transition - Fade out slowly than Fade in



回答4:


Examples with fadeOut will NOT work with your html code. The reason is simple - mouseout or second function of the hover will be triggered at the end of the fadeOut animation as the image will get display:none property. Look at my code http://jsfiddle.net/TW232/

$('div').hover(function(){
    $(this).width($('img', this).width()).height($('img', this).height());
    $('img', this).stop(true,true).fadeOut('fast');
    }, function(){
    $('img', this).stop(true,true).fadeIn('fast');
});​

html:

<div>
 <img id="show" src="http://img14.imageshack.us/img14/9698/29588166.jpg" alt=""/>
</div>​

and css:

div {background:red; width:0px;}​


来源:https://stackoverflow.com/questions/9492414/jquery-fadeout-on-hover

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