将 jQuery scrollTop 转换为 Javascript 以反转滚动方向

问题描述 投票:0回答:1

我正在尝试将一些 jQuery 代码转换为 Vanilla JS。目的是反转容器的滚动方向。 jQuery 版本运行良好。然而我正在努力将其转换为 JS。

$(window).on('scroll',function(){
    $(".container").css('bottom',$(window).scrollTop()*-1);
});

JS:

const container = document.querySelector('.container');

var scroll =  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

window.addEventListener('scroll', function() {
    container.style.bottom = "";
});

谢谢你。

javascript scrolltop
1个回答
0
投票

正如我在第一条评论中所说:

1.) 创建一个返回当前滚动位置的函数

function getScrollPosition() {
  return Math.max(
    window.scrollY, // same as window.pageYOffset
    document.documentElement.scrollTop,
    document.body.scrollTop
  );
}

2.) 在每个滚动事件上调用该函数

window.addEventListener('scroll', function () {
  const scrollY = getScrollPosition();
  // ... rest elided ...
});

3.) 将返回值/滚动位置与负乘(* -1)分配给容器上的

.style.bottom
属性,不要忘记将“px”添加到值上

window.addEventListener('scroll', function () {
  const scrollY = getScrollPosition();
  container.style.bottom = scrollY + 'px'; // doesn't matter if " or ' is used
});

尝试一下:

const container = document.querySelector('.container');

function getScrollPosition() {
  return Math.max(
    window.scrollY, // same as window.pageYOffset
    document.documentElement.scrollTop,
    document.body.scrollTop
  );
}

window.addEventListener('scroll', function () {
  const scrollY = getScrollPosition();
  container.style.bottom = scrollY + 'px'; // doesn't matter if " or ' is used
});
body {
  min-height: 110vh;
}

.container {
  position: absolute;
  bottom: 0;
  left: calc(50% - 100px);
  width: 200px;
  height: 200px;
  border: 1px solid red;
}
<div class="container">
  I move
</div>

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