我正在建立一个新的投资组合网站,但在从div返回一致的y轴值时遇到问题。
我尝试使用scrollTop,目前使用getBoundingClientRect从div中获取axis和top + bottom值来更改滚动背景颜色。
我的HTML:
<main class="main flex">
<header id="mainContent" class="main__content flex">
<h1 id="contentTitle" class="content__title">I design things that communicate.</h1>
</header>
<article id="coverPg" class="main__cover flex work__article--active">
<img alt="div1" data-category="Print, Typography, Layout" data-bg="7e288b" class="cover__item" src="media/TT5.jpg" />
<img alt="div2" data-category="Print, Illustration, Typography" data-bg="CFD4CE" class="cover__item" src="media/hl6.jpg" />
<img alt="div3" data-category="Poster, Web, UI/UX" data-bg="7CB8C0" class="cover__item" src="media/t2.jpg" />
<img alt="div4" data-category="Web, UI/UX, Mobile" data-bg="7CB8C0" class="cover__item" src="media/t2.jpg" />
</article>
</main>`
我的CSS:
body {
background-color: var(--yellow);
height: 100%;
overflow-x: hidden;
overflow-y: hidden;
position: relative;
-webkit-transition: all .5s ease-in-out;
-moz-transition: all .5s ease-in-out;
-o-transition: all .5s ease-in-out;
-ms-transition: all .5s ease-in-out;
transition: all .5s ease-in-out; }
.main {
position: relative;
height: 100%;
z-index: 1;
overflow-y: auto;
padding-right: 17px;
box-sizing: content-box; }
.main__content {
position: fixed;
right: 0;
left: 0;
margin-top: -2.5vh;
height: 110px;
z-index: 100; }
.work__article--active {
position: relative;
height: 100%;
padding-top: 85%;
display: inline-block; }
.cover__item {
max-height: 50vh;
width: 100%;
object-fit: cover;
margin-top: 7.5%;
margin-bottom: 7.5%;
box-sizing:border-box; }
有问题的JS函数:
trackCover = function(workDOM) {
var contentPos = document.getElementById(DOM.content).getBoundingClientRect();
var percentage = Math.round(bodyDOM.getBoundingClientRect().height / 7.5);
for (var i = 0; i < workDOM.length; i++) {
(function(i) {
var workPos = workDOM[i].getBoundingClientRect();
var active = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true && workPos.top < (contentPos.y + percentage) && workPos.bottom > (contentPos.y - percentage)) {
console.log(`${workDOM[i].alt} is ${workPos.y}`)
}
}, { threshold: [0] });
active.observe(workDOM[i]);
})(i)
}
};
应该发生的事情是,一旦元素在main__content的值范围内滚动(这里是contentPos +/-百分比),它将从滚动到div的数据值中拉出。
它最初是有效的,但在向后滚动(沿任何方向)时,我会遇到一个y轴值变化的墙(5到20之间的任何位置),滚轮移位从〜-200到〜 500。