猿问

滚动位置> 0后如何平滑向下滚动到元素?

我的页面顶部有一个全屏预告片。当用户开始滚动时,我希望整个页面自动平滑地向下滚动到以下部分。


不幸的是,以下代码不起作用。如前所述,它根本不会滚动,并且当我不将scrolling变量设置为true以避免多次执行scrollIntoView时,它非常慢。


使用香草JS修复此问题的好方法是什么?


示例,在Chrome中进行了测试:


let scrolling = false;


window.onscroll = () => {

  const offset = window.pageYOffset;

  if (offset > 0 && offset < window.innerWidth && !scrolling) {

    scrolling = true;

    document.querySelector('.somecontent').scrollIntoView({behavior:'smooth'});

  }

  

  if (offset >= window.innerWidth) {

    scrolling = false;

  }

}

.someteaser {

  background: blue;

  height: 100vh;

  width: 100vw;

}


.somecontent {

  background: red;

  height: 200vh;

  width: 100vw;

}

<div class="someteaser"></div>

<div class="somecontent"></div>

因此,问题在于行为:“平滑”选项。没有它,滚动将起作用,但是当然不再平滑了。这似乎是scorllIntoView上的错误,我不太了解。我的临时解决方案使用此脚本,该脚本可以正常运行:https : //github.com/cferdinandi/smooth-scroll


DIEA
浏览 123回答 1
1回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答