1.首先分析一下,兩側廣告跟隨,就是在滑鼠向下滾動時,左右兩幅圖也跟著向下滾動相等的距離
2.可以知道假設滑鼠向下滾動了100px的話,那么兩個圖片也是向下滾動了100px,他的位置就是100加上圖片距離父標簽的距離
3.現在還要實作一個圖片的緩慢移動,就是設定一個計時器,分步驟將圖片一步一步的走到最終的位置
4.用當前螢屏被卷去的長度在加上距離上螢屏的高度就是圖片應該到達的位置y,此時用y減去當前圖片距離頂部的距離,就是圖片到達y的距離sum,
5.要實作緩慢移動的話可以將sum/10,圖片一點一點的移動就實作了緩慢移動
代碼如下
<body>
<div class="head_p"></div>
<div class="main_1"></div>
<div class="main_2"></div>
<div class="left_p"></div>
<div class="right_p"></div>
<script>
var y = 0;
var l = document.querySelector('.left_p');
var r = document.querySelector('.right_p');
window.onscroll = function () {
var y = window.pageYOffset;
animate(l, y + 100);
animate(r, y + 100);
}
function animate(ele, target) {
clearInterval(ele.timer);
ele.timer = setInterval(function () {
var step = (target - ele.offsetTop) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
ele.style.top = ele.offsetTop + step + "px";
console.log(step);
if (Math.abs(target - ele.offsetTop) < Math.abs(step)) {
ele.style.top = target + "px";
clearInterval(ele.timer);
}
}, 10);
}
</script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/152799.html
標籤:其他
