简体   繁体   中英

how to display a div1 on hovering div2 and fading div1 on mouseout?

I want to display div1 on hovering div2 and disappear div1 only if mouse is not hovering both div1 and div2 .

I tried using the following CSS and jquery. But the div1 disappears immadiately after unhovering div2 and i am unable to access the content of div1.

  $(document).ready(function() { $('.about').hover( function() { $('.showsection').slideDown(800).addClass('show'); } , function() { $('.showsection').slideToggle(800); }); }); 
 .showsection{ display:none; } .show{ display:block; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class=about> <h1>About</h1> </div> <div class="showsection"> <h1>Title</h1> </div> 

The CSS :hover attribute will only control the element which it is assigned to, in your case presumable div1. So, you are going to have to use JavaScript.

With JavaScript attach a mouseenter and mouseleave event to div1. Inside those event listener functions, control what you want div2 to do.

That's basically how to do it.

This could be done by attaching mouseenter and mouseleave events to the elements you want to show/hide.

These are the requirements:

  • Show showsection when mouse enters about . This can be done using mouseenter on about
  • Hide showsection when mouse is not hovering over both showsection and about . This actually means checking two things: the mouse is not hovering showsection when it leaves about and the mouse is not hovering about when it leaves showsection . That means we have to attach mouseleave events to both showsection and about .

The below snippet should help.

 // JS $(document).ready(function() { // mouse enters .about $('.about').on('mouseenter', function() { $('.showsection').slideDown(800); }); // mouse leaves .about $('.about').on('mouseleave', function() { // if mouse is not hovering over .showsection hide it if (!$('.showsection').is(':hover')) { $('.showsection').slideToggle(800); } }); // mouse leaves .showsection $('.showsection').on('mouseleave', function() { // if mouse is not hovering over .about hide .showsection if (!$('.about').is(':hover')) { $('.showsection').slideToggle(800); } }); }); 
 /* CSS */ .showsection { display: none; background: #ddd; } h1 { margin: 0; } .about { background: #eee; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class=about> <h1>About</h1> </div> <div class="showsection"> <h1>Title</h1> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM