Hover over one element shows div, and show second

2019-07-10 04:52发布

I have a div with a hover event listener, when I hover over it, it displays some image in a separate div. What I would like to do is:

If I hover over the first div, the second div should be visible and after certain time it should fade out (so far so good, I have the code for this).

While the second div is displayed (2000 ms), if hovered, it shouldn't fade. If mouse leaves the second div, it should fade.

In this example, when I hover over the blue square, the second one is show. If I hover over the first, and then the second one, the green one should be visible until mouse is out of it (green one).

Can you please help me?

 $("#liOffices").hover(
   function() {
     $("#element").fadeIn(20, function() {
       $("#element").addClass("visible1");
       $("#element").removeClass("second");
     });


   }, function() {
     $("#element").fadeOut(2000, function() {
       $("#element").removeClass("visible1");
       $("#element").addClass("second");
     });
   }
 );
.first {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #36F;
}
.second {
  position: absolute;
  margin-left: 150px;
  width: 100px;
  height: 100px;
  background-color: #3C6;
  display: none;
}
.visible1 {
  position: absolute;
  margin-left: 150px;
  width: 100px;
  height: 100px;
  background-color: #3C6;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="liOffices" class="first"></div>



<div id="element" class="second"></div>

1条回答
做自己的国王
2楼-- · 2019-07-10 04:54

Try to bind hover event for #element also. That will fix the issue that you are facing. And use .stop() to clear the on going animation queue.

 $("#liOffices,#element").hover(
   function() {
     $("#element").stop().fadeIn(20, function() {
       $("#element").addClass("visible1");
       $("#element").removeClass("second");
     });


   }, function() {
     $("#element").stop().fadeOut(2000, function() {
       $("#element").removeClass("visible1");
       $("#element").addClass("second");
     });
   }
 );
.first {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #36F;
}
.second {
  position: absolute;
  margin-left: 150px;
  width: 100px;
  height: 100px;
  background-color: #3C6;
  display: none;
}
.visible1 {
  position: absolute;
  margin-left: 150px;
  width: 100px;
  height: 100px;
  background-color: #3C6;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="liOffices" class="first"></div>



<div id="element" class="second"></div>

查看更多
登录 后发表回答