首先,看看下面的代码:

window.addEventListener('scroll', () => {
  document.body.style.setProperty('--scroll', window.pageYOffset / (document.body.offsetHeight - window.innerHeight));
}, false);
.top-line {
    width: 7px;
    height: 100%;
    position: absolute;
    bottom: auto;
    left: 0;
    z-index: 2000;
    background-color: #f00;
    border-radius: 0;
    animation: bottom-line 1s linear;
    -webkit-animation: bottom-line 1s linear;
    -moz-animation: bottom-line 1s linear;
    -o-animation: bottom-line 1s linear;
    -ms-animation: bottom-line 1s linear;
}

@keyframes bottom-line {
    to {
      background-color: #f00;
      height: 0%;
    }
  }

 :root .top-line {
    animation-play-state: paused;
    animation-delay: calc(var(--scroll) * -1s);
    animation-iteration-count: 1;
    animation-fill-mode: both;
}
<div class="top-line"></div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

正如您在上面的代码中看到的那样,左侧导航栏开始随着主页滚动而移动.但这种移动是错误的,因为左侧滚动条在主页滚动到达终点之前到达终点.

我希望左滚动条首先为0%(隐藏),然后当主滚动开始从上到下移动时,左滚动条以与主滚动相反的方向从下到上移动.

推荐答案

这可以通过纯CSS来实现.改用animation-timeline:scroll(y).(Can I use animation-timeline on my browser?)

当您向下滚动时,动画会向前推进并增加top-line.此外,它应该使用position:fixed来根据视区保持位置.

.filler {
  height: 300vh;
}

.top-line {
  width: 7px;
  position: fixed;
  /*updated*/
  bottom: 0;
  z-index: 2000;
  background-color: #f00;
  border-radius: 0;
  animation: bottom-line 1s linear;
  animation-timeline: scroll(y);
  /*added*/
}

@keyframes bottom-line {
  0% {
    height: 0vh;
  }
  100% {
    height: 100vh;
  }
}
<div class="top-line"></div>
<div class="filler"></div>


如果不支持animation-timeline:scroll(),作为解决方案,一种解决方案是使用JavaScript来更新高度.

function getScrollPercent() {
  var h = document.documentElement,
    b = document.body,
    st = 'scrollTop',
    sh = 'scrollHeight';
  return (h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight) * 100;
}

function update() {
  document.getElementById("left-line").style.height = getScrollPercent() + "vh";
}

window.addEventListener('scroll', () => {
  update();
});
update();
.filler {
  height: 300vh;
}

.top-line {
  width: 7px;
  height: 0vh;
  position: fixed;
  bottom: 0;
  z-index: 2000;
  background-color: #f00;
  border-radius: 0;
}
<div id="left-line" class="top-line"></div>
<div class="filler"></div>

Javascript相关问答推荐

橡皮擦完全让画布变成白色

一次仅播放一个音频

vscode扩展-webView Panel按钮不起任何作用

MongoDB中的引用

为什么ngModel不能在最后一个版本的Angular 17上工作?'

如何在不创建新键的情况下动态更改 map 中的项目?

为什么当我解析一个promise时,输出处于挂起状态?

使用JQuery单击元素从新弹出窗口获取值

实现JS代码更改CSS元素

使用GraphQL查询Uniswap的ETH价格

如何在Svelte中从一个codec函数中调用error()?

映射类型定义,其中值对应于键

如何在箭头函数中引入or子句?

如何在JAVASCRIPT中合并两组对象并返回一些键

回溯替代方式

Google脚本数组映射函数横向输出

如果NetSuite中为空,则限制筛选

在HTML中使用meta标记来指定定制元数据以用于使用JavaScript进行检索是不是一个坏主意?

JS/css:将数字输入的S函数和可调整大小的元素S函数绑定在一起

如何在单击Search按钮时更新Reaction组件?