簡體   English   中英

JavaScript 滾動事件偵聽器不起作用

[英]JavaScript scroll event listener not working

我有一個腳本可以為我的頁面上的一些項目設置動畫。 但是,由於頁眉、導航和橫幅的原因,頁面加載時不會正確看到這些點。 所以我希望在用戶向下滾動到足以看到它之后加載動畫。 在查找了不同的代碼之后,我想出了下面的代碼。 但是,無論我做什么,滾動事件似乎都沒有響應。 我什至試圖通過向控制台發送滾動數據來測試它,但一無所獲。

 "use strict"; var pointsArray = document.getElementsByClassName('point'); var animatePoints = function (points) { function revealPoints() { for (var i = 0; i < points.length; i++) { // animate all 'point' classes points[i].style.opacity = 1; points[i].style.transform = "scaleX(1) translateY(0)"; points[i].style.msTransform = "scaleX(1) translateY(0)"; points[i].style.WebkitTransform = "scaleX(1) translateY(0)"; } // end loop } // end revealPoints() revealPoints(); // show animations }; window.onload = function () { if (window.innerHeight > 950) { // if user can see it, just do the animation animatePoints(pointsArray); } var sellingPoints = document.getElementsByClassName('selling-points')[0]; var scrollDistance = sellingPoints.getBoundingClientRect().top - window.innerHeight + 200; window.addEventListener("scroll", function (event) { console.log("Current offset from the top is " + sellingPoints.getBoundingClientRect().top + " pixels"); if (document.documentElement.scrollTop || document.body.scrollTop >= scrollDistance) { animatePoints(pointsArray); } }); };

我認為您的問題是window.onload事件永遠不會在您的情況下觸發。

你可以不使用onload嗎? 像這里https://jsfiddle.net/ovkycmem/或加載https://jsfiddle.net/ovkycmem/1

但是您需要確保其他腳本不會覆蓋window.onload函數。 因此,要找出您的問題是什么,請發布更多代碼或至少不工作的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM