如何解决使用滚动方向更改div位置
我一直在寻找一种仅使用Javascript根据滚动方向更改div位置的方法。
我在great resource的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;
}
JAVASCRIPT
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位置,或尝试执行类似操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。