简体   繁体   English

当顶部边框触及视口顶部时获取 div 的数据

[英]get data of a div when its top border touches the top of viewport

Three divs on a page - each of them has 100vh height.页面上的三个 div - 每个都有100vh高度。

By scrolling up and down, I need to get data-x of a div when its top border touches the top of viewport.通过上下滚动,我需要在其顶部边框接触视口顶部时获取 div 的data-x

And only when scrolling, not by loading the page.并且仅在滚动时,而不是通过加载页面。

In the example below on scrolling down console should be:在下面的示例中,向下滚动控制台应该是:

ipsum
dolor

and on scrolling back to top:并滚动回到顶部:

ipsum
lorem

Here is my try, but without success to get such a control.这是我的尝试,但没有成功获得这样的控制。

please help请帮忙

 var cards = [...document.querySelectorAll('.card')] let options = { rootMargin: '100%' }; function onIntersect(entries) { entries.forEach((entry) => { console.log(entry.target.dataset.x); }); } const io = new IntersectionObserver(onIntersect, options) cards.forEach((card) => { io.observe(card) })
 .card{height:100vh;}.carda{background:orange;}.cardb{background:lightblue;}.cardc{background:silver;}
 <div class='card carda' data-x='lorem'></div> <div class='card cardb' data-x='ipsum'></div> <div class='card cardc' data-x='dolor'></div>

You have to detect if the page was scrolled , and console.log only that card which isIntersecting :您必须检测页面是否scrolled ,并且console.log仅检测isIntersecting的卡片:

 var scrolled = false; document.addEventListener('scroll', () => scrolled = true, {once: true}); var cards = [...document.querySelectorAll('.card')] let options = { threshold: .7 }; function onIntersect(entries) { entries.forEach((entry) => { if (scrolled && entry.isIntersecting) { console.log(entry.target.dataset.x); } }); } const io = new IntersectionObserver(onIntersect, options) cards.forEach((card) => { io.observe(card) })
 .card { height: 100vh; }.carda { background: orange; }.cardb { background: lightblue; }.cardc { background: silver; }
 <div class='card carda' data-x='lorem'></div> <div class='card cardb' data-x='ipsum'></div> <div class='card cardc' data-x='dolor'></div>

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

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