[英]Changing div position with scroll direction
我正在尋找一種僅使用 Javascript 根據滾動方向更改 div 位置的方法。
我在CodePen上從lehollandaisvolant找到了一個很好的資源,這讓我走上了正軌。 (非常感謝!)此代碼輸出顯示用戶滾動方向的 html 內容。
這是原始代碼:
HTML
<p>Because i’m sick of using tons of shit for this basic function.</p>
<p>This uses no timing functions, no jQuery and fits everywhere.</p>
<pre>
Scroll me.
Scroll me.
Scroll me.
Scroll me.
Scroll me.
Scroll me.
</pre>
<div id="info-box" data-scroll-direction="no scrolling yet, go on!">
Your last scolling direction was:
</div>
CSS
#info-box {
padding: 50px;
position: fixed;
background: #fafafa;
box-shadow: 3px 3px 3px silver;
top: 20px;
right: 20px;
}
#info-box::after {
content: attr(data-scroll-direction);
}
pre {
line-height: 250px;
}
爪哇腳本
var scrollPos = 0; // Initial state
window.addEventListener('scroll', function(){ // adding scroll event
// detects new state and compares it with the new one
if ((document.body.getBoundingClientRect()).top > scrollPos)
document.getElementById('info-box').setAttribute('data-scroll-direction', 'UP');
else
document.getElementById('info-box').setAttribute('data-scroll-direction', 'DOWN');
// saves the new position for iteration.
scrollPos = (document.body.getBoundingClientRect()).top;
});```
但是,為了更改 div 位置,我只是更改了 If/Else 語句以適合我想要的 css 標准:
// Initial state
var scrollPos = 0;
// adding scroll event
window.addEventListener('scroll', function(){
// detects new state and compares it with the new one
if ((document.body.getBoundingClientRect()).top > scrollPos)
document.getElementById('info-box').style.margin = '100px 0 0 0';
else
document.getElementById('info-box').style.margin = '0px 0 0 0';
scrollPos = (document.body.getBoundingClientRect()).top;
});
具體來說:
if ((document.body.getBoundingClientRect()).top > scrollPos)
document.getElementById('info-box').style.margin = '100px 0 0 0';
else
document.getElementById('info-box').style.margin = '0px 0 0 0';
希望有人會發現這在嘗試根據滾動方向更改 div 的 css 位置或嘗試執行類似操作時很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.