简体   繁体   English

使用 JavaScript 在滚动上显示 Div

[英]Show Div on Scroll using JavaScript

I am attempting to reveal divs as the user scrolls through the page.我试图在用户滚动页面时显示 div。 I am attempting to do this using javascript and css without any additional libraries.我正在尝试使用 javascript 和 css 来执行此操作,而无需任何其他库。

Currently, I have a setup using jQuery that gets the job done but I am having issues finding a javascript only solution.目前,我有一个使用 jQuery 的设置,可以完成工作,但我在寻找 javascript 唯一解决方案时遇到问题。 I do not want the div to appear in a certain position, just simply as it appears in the user's viewport.我不希望 div 出现在某个 position 中,就像它出现在用户的视口中一样。

I am using opacity: 0 to hide the div, and then using $(this).animate({'opacity':'1'},500);我正在使用 opacity: 0 隐藏 div,然后使用$(this).animate({'opacity':'1'},500); to display.显示。

I have been unable to find a similar javascript option that does not use a library or jQuery.我一直找不到不使用库或 jQuery 的类似 javascript 选项。

Can I achieve the code below using javascript?我可以使用 javascript 实现下面的代码吗?

A working jquery solution example is:一个有效的 jquery 解决方案示例是:

 $(document).ready(function() { /* Every time the window is scrolled... */ $(window).scroll( function(){ /* Check the location of each desired element */ $('.scroll-in').each( function(i){ var bottom_of_object = $(this).offset().top + $(this).outerHeight(); var bottom_of_window = $(window).scrollTop() + $(window).height(); /* If the object is completely visible in the window, fade it it */ if( bottom_of_window > bottom_of_object ){ $(this).animate({'opacity':'1'},500); } }); }); });
 #container { height:2000px; } #container div { margin:50px; padding:50px; background-color:blue; }.scroll-in { opacity:0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> <div>Show</div> <div>Show</div> <div class="scroll-in">Fade In</div> <div class="scroll-in">Fade In</div> <div class="scroll-in">Fade In</div> </div>

What you want to use is an intersection observer - this is a html5 method of determinig when an element is in the vieport.您要使用的是intersection observer器 - 这是一种 html5 确定元素何时位于视口中的方法。 This can be used for funky effects - eg autoplaying a video - only when the video in in the viewport - (eg: Facebook)... or lazy loading images.这可以用于时髦的效果 - 例如自动播放视频 - 仅当视频在视口中时 - (例如:Facebook)......或延迟加载图像。

Note that you can specifiy the amount by which the element must be in the viewport for the effect to take place - this is the "threshold" in the config options.请注意,您可以指定元素必须在视口中的数量才能发生效果 - 这是配置选项中的“阈值”。

Also note that intersection observers ARE NOT supported in IE - so you will either need to use a polyfill or have a fallback like I have provided in the example.另请注意,IE 不支持交叉点观察器 - 因此您将需要使用 polyfill 或像我在示例中提供的那样使用后备。

 let paragraphs = document.querySelectorAll('p'); if ('IntersectionObserver' in window) { // IntersectionObserver Supported let config = { root: null, rootMargin: '0px', threshold: 1 }; let observer = new IntersectionObserver(onChange, config); paragraphs.forEach(paragraph => observer.observe(paragraph)); function onChange(changes, observer) { changes.forEach(change => { if (change.intersectionRatio > 0) { // Stop watching and load the image showParagraph(change.target); observer.unobserve(change.target); } }); } } else { // IntersectionObserver NOT Supported paragraphs.forEach(paragraph => showParagraph(paragraph)); } function showParagraph(paragraph) { paragraph.classList.add('fade-in'); }
 p { opacity: 0 }.fade-in { animation-name: fadeIn; animation-duration: 1000ms; animation-timing-function: cubic-bezier(0, 0, 0.4, 1); animation-fill-mode: forwards; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
 <h2>Scroll me to see paragraphs appear when the are fully within the viewport </h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<p> <p> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<p> <p> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

You could accomplish this with plain javascript using an IntersectionObserver .您可以使用IntersectionObserver使用普通的 javascript 来完成此操作。 Here's a quick skeletal example:这是一个简单的骨架示例:

 const callback = (entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { if (entry.intersectionRatio >.5) { entry.target.classList.add('active'); } else { entry.target.classList.remove('active'); } } }); } const observer = new IntersectionObserver(callback, {threshold: 1}); document.querySelectorAll('div').forEach(d => observer.observe(d));
 div { background: bisque; min-height: 100px; width: 50%; margin-bottom: 0.5rem; opacity: 0; transition: all 0.5s ease-out; } div.active { background: tomato; width: 100%; opacity: 1; }
 <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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