我要做的就是使页面上的一个元素(最简单的div)滚动得比页面上的其他元素慢或快。例如,滚动时,此特定的div将以其他项目的速度的50%或200%等移动。
这看起来很简单,但是我找不到任何示例。另外,我不想使用JQuery,别人的草图/过于复杂的3rd party插件等。只是简单,干净,CSS和JS。
答案 0 :(得分: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>