javascript - 单击按钮时如何将滚动条向下移动到页面的特定坐标
问题描述
嗨,伙计们,由于某些原因,当我尝试向下移动滚动条以使页面的某个部分成为焦点时,scrollTo 对我根本不起作用这是我的代码。
var xplore = document.querySelector('.btn-explore');
xplore.addEventListener('click', function() {
window.scrollTo(0, 785);
}
)
有谁可以帮我离开这里吗?页面根本不滚动,或者它与我的css有关,我需要位置或溢出属性吗?提前致谢。
解决方案
问题可能是您的body
orhtml
标签没有足够大的高度来滚动浏览。
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 - 如何将 jquery 元素的“id”参数传递给具有数组的函数
- python - 与时间序列一起使用时,这是熊猫 ewm 中的错误吗?
- heroku - Gitlab Autodeploy Laravel private repo composer install COMPOSER_AUTH env var not read
- log4j2 - JsonTemplateLayout - eventTemplate - 缺失值
- android - 跳过 kotlin 协程中的延迟
- node.js - 计算 haystack 中针的出现次数,无论 haystack char 顺序如何
- html - 除了引导日期时间选择器之外的黑色子弹
- performance - 火花日志中的 TID 是什么意思?
- javascript - 我需要在 JS 中创建一个“查看更多图片”按钮
- android - AlertDialog 按钮定位