简体   繁体   中英

Show/hide div or image when scrolling

Is there a way to show an image or a div when scrolling down a web page and hide it when not scrolling and vice versa?

So in the code below the red div would be displayed when not scrolling, and the green div would be displayed only when scrolling.

 .square { position: fixed; width: 100px; height: 100px; } .green { background: green; display: none; } .red { background: red; } .container { width: 100%; height: 3000px; }
 <div class="container"> <div class="square green"></div> <div class="square red"></div> </div>

The end goal is to achieve something like this: https://mailchimp.com/annual-report/ where the character appears to be walking when the user scrolls, and stands still when the user stops. Is this easily achievable?

You just need an eventListener that listen to a scroll event. However this has the issue that it only recoginze when you scroll but not when you stop scrolling. For that you can use this answer that explains how to listen for a "scroll-stop"

To make the code shorter and easier, I removed your display: none from the green box. I added a new class d-none that contains this proeprty now instead. By default it is added to the green box.

With classList.toggle('d-none') I can toggle class within both boxes which makes it easier then to address and then add or remove the class for every box on its own.

 var timer = null; var box = document.querySelectorAll('.square'); window.addEventListener('scroll', function() { if (timer !== null) { clearTimeout(timer); } else { box.forEach(el => el.classList.toggle('d-none')); } timer = setTimeout(function() { box.forEach(el => el.classList.toggle('d-none')); }, 150); }, false);
 .d-none { display: none; } .square { position: fixed; width: 100px; height: 100px; } .green { background: green; /* display: none; */ /* removed */ } .red { background: red; } .container { width: 100%; height: 3000px; }
 <div class="container"> <div class="square green d-none"></div> <div class="square red"></div> </div>

You just need a setTimeout function:

 (function($) { $(function() { $(window).scroll(function() { $('.square.red').show() $('.square.green').hide() clearTimeout($.data(this)); $.data(this, setTimeout(function() { $('.square.red').hide() $('.square.green').show() }, 250)); }); }); })(jQuery);
 .square { position: fixed; width: 100px; height: 100px; } .green { background: green; } .red { background: red; display: none; } .container { width: 100%; height: 3000px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="square green"></div> <div class="square red"></div> </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