gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:47:42 25 4
gpt4 key购买 nike

大家好,由于某些原因,当我尝试向下移动滚动条以使页面的某个部分获得焦点时,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com