2 回答

TA貢獻1811條經驗 獲得超4個贊
您需要添加選擇器來切換動畫類。而且您當前的 css 沒有足夠的高度來制作滾動窗口。這是一個簡單的片段來運行你的函數 onload、更新 onscroll 和切換類。
var dataAnimate = document.querySelector('[data-animate]');
function animateAfterPosition(scroll) {
dataAnimate.classList.toggle('active', window.scrollY <= scroll);
}
window.addEventListener("scroll", function() {
return animateAfterPosition(200);
});
.animateAfterPosition {
transition: attr(data-animate-time);
left: attr(data-animate-left);
top: attr(data-animate-top);
}
[data-animate] {
height: 1000px;
}
<body onload="animateAfterPosition(200)">
<h1 style="position: relative; top: 0; left: 0;"data-animate-left="50px" data-animate-top="50px" data-animate-time="0.2s" data-animate>Animation on scroll</h1>
</body>
小提琴:https ://jsfiddle.net/rafonzoo/phmg0u46/

TA貢獻1850條經驗 獲得超11個贊
簡約的解決方案
您可以使用函數中的前 4 個變量對其進行配置。我建議將指標類添加到正文本身,然后使用像body.beyond-that-point h1. 這樣,當滾動發生時,可以使多個標簽的行為有所不同。
你可以在這里測試
這個版本使用了更高級的效果,但背后的邏輯是一樣的。
https://deneskellner.com/stackoverflow-examples/62623588/index.html
<!doctype html>
<html>
<style>
body.beyond-that-point {background:silver;}
div.text {padding:75vh 0px;text-align:center;}
</style>
<body>
<div class="text">
Scroll me down and the background will change
</div>
<script>
setTimeout(function() {
var amount = 100; // how many pixels before the miracle happens
var beyondClass = 'beyond-that-point'; // this class will be added
var targetSelector = 'body'; // which element to add the class to
var checkMS = 20; // check scroll position every N milliseconds
var eClass = document.querySelector(targetSelector).classList;
setInterval(function() {
var y = window.scrollY;
var c = beyondClass;
var isBeyond = !!(y>=amount)?1:0;
if(isBeyond==1) if(!eClass.contains(c)) eClass.add(c);
if(isBeyond==0) if( eClass.contains(c)) eClass.remove(c);
},checkMS);
},1);
</script>
</body>
</html>
注意:有更好的方法來檢查 DOM 準備情況,但為了簡單起見,我setTimeout在這里使用。隨意改變它。
添加回答
舉報