使用滚动方向更改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位置,或尝试执行类似操作。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...