首页 > 解决方案 > 单击按钮时如何将滚动条向下移动到页面的特定坐标

问题描述

嗨,伙计们,由于某些原因,当我尝试向下移动滚动条以使页面的某个部分成为焦点时,scrollTo 对我根本不起作用这是我的代码。

var xplore = document.querySelector('.btn-explore');
    xplore.addEventListener('click', function() {
        window.scrollTo(0, 785);
      }
    )

有谁可以帮我离开这里吗?页面根本不滚动,或者它与我的css有关,我需要位置或溢出属性吗?提前致谢。

标签: javascript

解决方案


问题可能是您的bodyorhtml标签没有足够大的高度来滚动浏览。

body, html{
  height: 785px;
}
<button class="btn-explore">Explore</button>
<script>
var xplore = document.querySelector('.btn-explore');
xplore.addEventListener('click', function() {
     window.scrollTo(0, 785);
   }
)
</script>

如果你想在一定的毫秒内平滑滚动到一个位置,你可以使用window.requestAnimationFrame.

body, html{
  height: 785px;
}
<button class="btn-explore">Explore</button>
<script>
var xplore = document.querySelector('.btn-explore');
xplore.addEventListener('click', function() {
     scrollToSmoothly(785, 500);
   }
)
/*
   @param pos: the y-position to scroll to (in pixels)
   @param time: the exact amount of time the scrolling will take (in milliseconds)
*/
function scrollToSmoothly(pos, time) {
    var currentPos = window.pageYOffset;
    var start = null;
    if(time == null) time = 500;
    pos = +pos, time = +time;
    window.requestAnimationFrame(function step(currentTime) {
        start = !start ? currentTime : start;
        var progress = currentTime - start;
        if (currentPos < pos) {
            window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
        } else {
            window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
        }
        if (progress < time) {
            window.requestAnimationFrame(step);
        } else {
            window.scrollTo(0, pos);
        }
    });
}
</script>


推荐阅读