我正在嘗試制作一個側分頁欄,并且我希望它在頁面的不同部分進入視圖時改變顏色,所以我在 javascript 中使用 .getBoundingClientRect 。但是,每次滾動時,控制臺日志中元素的位置都是相同的,即使我一直滾動到底部也是如此。
有人可以幫助我,以便價值觀在他們應該改變的時候改變嗎?
var aboutPage = document.getElementById('about');
var aboutBounding = aboutPage.getBoundingClientRect();
window.addEventListener("scroll", () => {
console.log(aboutBounding);
if (
aboutBounding.top >= 0 &&
aboutBounding.left >= 0 &&
aboutBounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
aboutBounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
) {
console.log('In the viewport!');
} else {
console.log('Not in the viewport... whomp whomp');
}
})
/* SIDE PAGEINTATION */
.side-pagination {
position: fixed;
top: 50%;
left: 72px;
height: 138px;
width: 24px;
transform: translateY(-50%);
z-index: 10;
}
.page-circle {
width: 24px;
height: 24px;
border-radius: 50%;
background-color: #bcbcbc;
cursor: pointer;
}
.page-circle.menuactive {
background-color: var(--secondary-clr);
}
.page-circle:nth-child(1) {
margin-bottom: 14px;
}
.page-circle:nth-child(2) {
margin-bottom: 14px;
}
.page-circle:nth-child(3) {
margin-bottom: 14px;
}
.landing-main-body {
position: absolute;
top: 0%;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
background-color: gray;
}
.work-main-body {
position: absolute;
top: 200%;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
background-color: pink;
}
.about-main-body {
position: absolute;
top: 100%;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
background-color: purple;
}
<div class="side-pagination">
<div class="page-2 page-circle"></div>
<div class="page-3 page-circle"></div>
<div class="page-4 page-circle"></div>
</div>
<div class="landing-main-body">
</div>
<div class="about-main-body" id="about">
</div>
<div class="work-main-body" id="work">
</div>
編輯:我會在早上嘗試使用 IntersectionObserver,直到那時:D。
uj5u.com熱心網友回復:
當您將getBoundingClientRect
值存盤在滾動事件偵聽器之外時,您只存盤一次 rect 值。換句話說,它不會在滾動事件觸發時更新。
您需要像這樣讀取滾動事件偵聽器中getBoundingClientRect
的值:
var aboutPage = document.getElementById('about');
// var aboutBounding = aboutPage.getBoundingClientRect(); <-- Don't read it here
window.addEventListener("scroll", () => {
var aboutBounding = aboutPage.getBoundingClientRect(); // <-- Read it inside the scroll listener
console.log(aboutBounding);
if (
aboutBounding.top >= 0 &&
aboutBounding.left >= 0 &&
aboutBounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
aboutBounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
) {
console.log('In the viewport!');
} else {
console.log('Not in the viewport... whomp whomp');
}
})
uj5u.com熱心網友回復:
getBoundingClientRect()
不是反應性的。您將獲得read
操作的結果(在您讀取值的時間點)。
放置
var aboutBounding = aboutPage.getBoundingClientRect();
在函式之外,aboutBounding
將保持與讀取時相同的值。
將該行移到對每個scroll
事件執行的函式內,它將開始作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507068.html
標籤:javascript html css
上一篇:基于值的自定義排序資料陣列