开发者

How to properly crossfade text on hover with jquery

开发者 https://www.devze.com 2023-03-08 19:38 出处:网络
http://jsfid开发者_开发百科dle.net/mplungjan/8wf5E/ (works now - using .hover() ) The following obviously fails when hovering over the fading divs since that triggers the mouseout and in. I only need

http://jsfid开发者_开发百科dle.net/mplungjan/8wf5E/ (works now - using .hover() )

The following obviously fails when hovering over the fading divs since that triggers the mouseout and in. I only need the actual text to fade in and out, the wrapping divs are only for containment and debugging. A solution without position:absolute is preferred

<div id="container">
  <div id="one" class="fade">One</div>
  <div id="two" class="fade">Two</div>
</div>   

$(document).ready(function() {
  $("#container").mouseover(function () {
    $("#one").fadeOut("slow");
    $("#two").fadeIn("slow");
  }).mouseout(function () {
    $("#two").fadeOut("slow");
    $("#one").fadeIn("slow");
  });;
}); 

div { margin:3px; width:80px; height:80px; float:left; }
div#container { width: 100px; height:100px; border:1px solid black}
div#one { position:absolute; border:1px solid red;}
div#two { position:absolute; border:1px solid green; display:none; }


I would recommend using the hover function for this kind of functionality...

$(document).ready(function() {
  $("#container").hover(
    function(e) { 
      $("#one").fadeOut("slow");
      $("#two").fadeIn("slow");
    },
    function(e) {
      $("#two").fadeOut("slow");
      $("#one").fadeIn("slow");      
    }
  );
});

It fixes this particular problem.


Using mouseleave() instead of mouseout() seems to be better.
See here.


I think you are looking for this jQuery code :

$(document).ready(function() {
  $("#container").mouseenter(function () {
    $("#one").fadeOut("slow");
    $("#two").fadeIn("slow");
  }).mouseleave(function () {
    $("#two").fadeOut("slow");
    $("#one").fadeIn("slow");
  });;
});

EDIT : You can also do it using a bit of CSS3 magic ;)

div { margin:3px; width:80px; height:80px; float:left; }
div#container { width: 100px; height:100px; border:1px solid black}
div#one { position:absolute; border:1px solid red;-webkit-transition:opacity 0.5s ease-in-out;}
div#two { position:absolute; border:1px solid green; opacity:0;-webkit-transition:opacity 0.5s ease-in-out; }

div#container:hover #two{
 opacity:1;}
div#container:hover #one{
 opacity:0;}

=> http://jsfiddle.net/3WZKx/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消