使用滚动方向更改div位置

问题描述

我一直在寻找一种仅使用Javascript根据滚动方向更改div位置的方法

我在great resource的CodePen上找到了lehollandaisvolant,这使我步入正轨。 (非常感谢!)此代码输出的html内容显示用户滚动的方向。

这是原始代码

HTML

@H_502_10@<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位置,或尝试执行类似操作。