当我点击box1
时,滚动效果需要向下滚动到box2
(蓝色框的上边缘)。这在网络上效果很好,但我无法在移动设备上精确地复制效果。
document.getElementById('box1').addEventListener('click', function() {
window.scrollTo({
top: 507,
behavior: "smooth"
});
});
.box1 {
width: 100px;
height: 100px;
background-color: red;
}
.box2 {
width: 100px;
height: 100px;
background-color: blue;
}
.box3 {
width: 100px;
height: 100px;
background-color: green;
}
.gap {
width: 100%;
height: 400px;
background-color: yellow;
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title></title>
</head>
<body>
<div class="box1" id="box1"></div>
<div class="gap"></div>
<div class="box2" id="box2"></div>
<div class="gap"></div>
<div class="box3" id="box3"></div>
</body>
当在 iPhone 模拟器中点击 box1
时,scrollTo
将我带到黄色框的下半部分。
最佳答案
您正在滚动到特定坐标 (top: 507
),该坐标在移动设备上会有所不同。
使用 JavaScript 获取要滚动到的特定元素的顶部
坐标:
var box2 = document.getElementById("box2");
document.getElementById('box1').addEventListener('click', function() {
window.scrollTo({
top: box2.getBoundingClientRect().top,
behavior: "smooth"
});
});
关于javascript - 如何使 `window.scrollTo` 更精确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50261418/