简体   繁体   中英

Keep div visible when the mouse is over it

I have a div2 that fades away after 3 seconds and appears again on div1 or itself hover.

The problem is that it fades away again after 3 seconds and I want it to remain active while the mouse is over it.

Here's my code:

 $(document).ready(function(){ // div2 fades away after 3s setInterval(function(){ $(".div2").addClass("fade-away"); }, 3000); // div2 pops up on hover $(".div1, .div2").hover(function(){ $(".div2").removeClass("fade-away") }); });
 .div1 { width: 300px; height: 200px; background: pink; } .div2 { position: absolute; width: 300px; height: 50px; margin-top: -70px; background: lightblue; opacity: 1; } .fade-away { opacity: 0; }
 <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <div class="div1"></div> <div class="div2"></div>

Is there a way to make the div2 remain active while the mouse is over it with javascrit and css only? Sorry for my english.

Here is a quick and easy way to do it. You can do it by hovering over any class, I just did it in text for the example.

 .hide { display: none; } .myDIV:hover + .hide { display: block; color: red; }
 <body> <h2>Display an Element on Hover</h2> <div class="myDIV">Hover over me.</div> <div class="hide">I am shown when someone hovers over the div above.</div> </body>

You can use a boolean flag to do it.

Set the boolean to true when mouseenter and set it to false on mouseleave event.

https://jsfiddle.net/ramseyfeng/0nc2bw8f/

 $(document).ready(function() { let mouseIn = false; // div2 fades away after 3s setInterval(function() { if (!mouseIn) { $(".div2").addClass("fade-away"); } }, 3000); $('.div1').on('mouseenter', () => { mouseIn = true; }); $('.div1').on('mouseleave', () => { mouseIn = false; }); // div2 pops up on hover $(".div1, .div2").hover(function() { $(".div2").removeClass("fade-away") }); });
 .div1 { width: 300px; height: 200px; background: pink; } .div2 { position: absolute; width: 300px; height: 50px; margin-top: -70px; background: lightblue; opacity: 1; } .fade-away { opacity: 0; }
 <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <div class="div1"></div> <div class="div2"></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