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

问题描述 投票:-5回答:2

我想做的就是在页面上创建一个元素(div最简单)滚动比页面上的其他项目更慢或更快。例如,在滚动时,此特定div将以其他项目的速度的50%或200%移动,等等。

这似乎是一个简单,直截了当的事情,但我找不到任何这方面的例子。另外,我不想使用JQuery,别人的粗略/过于复杂的第三方插件等等。只是简单,干净,CSS和JS。

javascript html css parallax
2个回答
0
投票

所以我设法提出这个并不太复杂,但是,它确实相对于用户滚动速度滚动,但确实与滚轮,滚动条和键盘一起使用。

它也会上下滚动。

您可以根据自己的需要更改速度,但是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>

0
投票

好的,非常感谢@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

© www.soinside.com 2019 - 2024. All rights reserved.