[英]get data of a div when its top border touches the top of viewport
頁面上的三個 div - 每個都有100vh
高度。
通過上下滾動,我需要在其頂部邊框接觸視口頂部時獲取 div 的data-x
。
並且僅在滾動時,而不是通過加載頁面。
在下面的示例中,向下滾動控制台應該是:
ipsum
dolor
並滾動回到頂部:
ipsum
lorem
這是我的嘗試,但沒有成功獲得這樣的控制。
請幫忙
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>
您必須檢測頁面是否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.