繁体   English   中英

随滚动方向更改 div 位置

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM