javascript - 单击按钮时如何将页面向下移动滚动条到特定坐标

标签 javascript

大家好,由于某些原因,当我尝试向下移动滚动条以使页面的某个部分获得焦点时,scrollTo 对我来说根本不起作用 这是我的代码。

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

有人可以帮我吗?页面根本不滚动,或者是我的CSS的问题,我需要位置或溢出属性吗? 提前致谢。

最佳答案

问题可能是您的 bodyhtml 标记没有足够大的高度来滚动。

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>

关于javascript - 单击按钮时如何将页面向下移动滚动条到特定坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51829112/

相关文章:

javascript - 使用 Javascript 检索 UTC 时间戳

javascript - 使用带有提交按钮和重置按钮的 JavaScript 计算表单中的两个字段

javascript - 无法使用 FileReader 读取图像(请参阅更新 2)

javascript - Meteor.methods 与 ZeroMQ REQ/REP 从不返回答案

javascript - 在 JavaScript 中设置日期与时间的格式

javascript - fetch res.json 继续返回 Unresolved promise

javascript - 如何等待 IONIC(AngularJS) 中所有 js 脚本加载完成?

javascript - 在预提交中运行 ESLint 不会因警告而停止

Javascript onend 正在检测视频的结尾

javascript - 如何修改 CSS3 滚动框动画无限循环而不是重新开始?