如何使用纯 CSS 或 CSS/JS(不使用 JQuery)使一个 div 的滚动速度比页面上的其他项目慢或快?

How do I make one div scroll slower or faster than other items on the page, using pure CSS or CSS/JS (without JQuery)?

我只想让页面上的一个元素(div 最简单)比页面上的其他项目滚动得慢或快。例如,滚动时,这个特定的 div 将以其他项目速度的 50% 或 200% 移动,等等。

这看起来是一件很简单、直接的事情,但我找不到这方面的例子。另外,我不想使用 JQuery、别人的粗略/过于复杂的第 3 方插件等。只是简单、干净、CSS 和 JS。

所以我想出了一个不太复杂的方法,但是,它确实相对于用户的滚动速度滚动,但确实适用于滚轮、滚动条和键盘。

它也会上下滚动。

您可以更改速度以满足您的需要,但 10 可以让我的滚动速度一直保持在可见范围内,但在更快或使用 Page Down 时将它留在后面。

document.addEventListener("DOMContentLoaded", function DomContentLoaded(){
  //Get the element you want to slow down;
  var slowDiv = document.getElementById('slowDiv');
  //Set its style.top to be the offsetTop so if style.top is not set, it will still work.
  slowDiv.style.top = slowDiv.offsetTop + 'px';
  //set the last scrollTop to use for direction
  var lastScrollTop = 0;
  //Get the element you are scrolling against
  var relativeSpeedDiv = document.getElementById('main');


  var moveLittle = function MoveLittle(speed, scrollY) {
    //Get the current top of the slow element
    var topVal = parseInt(slowDiv.style.top);
    //Check scroll direction
    if (isScrollingDown(scrollY)) {
      topVal = topVal + speed;
    } else {
      topVal = topVal - speed;
    }
    //Set new top of slow element
    slowDiv.style.top = topVal + 'px';
  };

  var isScrollingDown = function IsScrollingDown(scrollY) {
    var retVal = false;
    if (scrollY > lastScrollTop) {
      retVal = true;
    }
    lastScrollTop = scrollY;
    return retVal;
  };

  window.onscroll = function WindowScroll() {
    //Send speed and current scroll Y
    moveLittle(10, this.scrollY);
  }

});
.biggestBig {
    margin: auto;
    align-self: center;
    width: 90%;
    min-height: 9999em;
}

.faded {
    background: linear-gradient(gray, black);
}

.slow {
    width: 2em;
    height: 2em;
    background-color: #ee9b0b;
    position: absolute;
}
<div id="mainDiv" class="biggestBig faded">
    <div id="slowDiv" class="slow"></div>
</div>

好的,感谢@ajaypane 的回答,但实际上我想出了一个更简单的方法。我不敢相信没有人这样做过 - 它远没有我见过的其他东西复杂。

JS

function parallax() {
    var s = document.getElementById("floater");
  var yPos = 0 - window.pageYOffset/5;  
  s.style.top = 50 + yPos + "%"; }

window.addEventListener("scroll", function(){
    parallax(); 
});

CSS

.section { position: relative; width: 100vw; height: 15vw; }
.object-in-3d { 
  margin-left: 45vw;
  width: 10vw; 
  height: 10vw; 
  background-color: #41ebf4; }

.float-center { 
  position: absolute; 
  top: 50%; }

#red { background-color: #f44141; }
#yellow { background-color: #f48342; }
#green { background-color: #f4dc41; }

#floater {}

HTML

<div class="section" id="red">&nbsp;</div>

<div class="section" id="yellow">
  <div class="object-in-3d float-center" id="floater">&nbsp;</div>
</div>

<div class="section" id="green">&nbsp;</div>

它在 codepen 中,在这里:

https://codepen.io/escapetomars/pen/EeLmpp