javascript - 使用 window.scrollTo({top: 50}) 与 window.scrollTo(0, 50) 有区别吗?
问题描述
我目前正在使用window.scrollTo({top: 50})
一个 React 函数,它工作得很好。
但是,window.scrollTo
旧版本的 Android 不支持将对象传递给(这里有一个关于详细信息的问题)。
我已经切换到 using window.scrollTo(0, 50)
,它的性能完全符合我的需要(以 50px 的偏移量滚动到顶部)。我已经在多个浏览器中对此进行了测试,它似乎工作正常。
以这种方式使用 XY 坐标与为对象提供top
字段相比有什么缺点吗?我查看了 MDN,但没有比较这两种方法的信息。
解决方案
scrollTo({top: 50})
将保持水平滚动不变,但scrollTo(0, 50)
将设置水平和垂直滚动。如果你想水平滚动也改变,你很好。否则,您将需要使用scrollTo(window.scrollX, 50)
.
这是一个scrollTo({top: 50})
不改变水平滚动的例子:
const marker = Array.from(Array(26), (_, i) => String.fromCharCode(97 + (i % 26)) + " ").join("");
let text = "";
for (let y = 1; y <= 200; ++y) {
text += marker.substring(0, y * 2) + "\n";
}
document.querySelector(".x").innerText = text;
setTimeout(() => {
console.log("Scrolling to 100, 100");
window.scrollTo(20, 100);
setTimeout(() => {
console.log("Scrolling to {top: 50}");
window.scrollTo({top: 50});
setTimeout(() => {
console.log(`window.scrollX = ${window.scrollX}`);
}, 100);
}, 800);
}, 800);
.x {
width: 2000px;
height: 2000px;
white-space: pre;
font-family: sans-serif;
}
<div class="x"></div>
...但scrollTo(0, 50)
确实:
const marker = Array.from(Array(26), (_, i) => String.fromCharCode(97 + (i % 26)) + " ").join("");
let text = "";
for (let y = 1; y <= 200; ++y) {
text += marker.substring(0, y * 2) + "\n";
}
document.querySelector(".x").innerText = text;
setTimeout(() => {
console.log("Scrolling to 100, 100");
window.scrollTo(20, 100);
setTimeout(() => {
console.log("Scrolling to 0, 50");
window.scrollTo(0, 50);
setTimeout(() => {
console.log(`window.scrollX = ${window.scrollX}`);
}, 100);
}, 800);
}, 800);
.x {
width: 2000px;
height: 2000px;
white-space: pre;
font-family: sans-serif;
}
<div class="x"></div>
推荐阅读
- ffmpeg - 来自 VBS 的 FFMPEG
- javascript - 在打字稿中找到数组值的交集
- python-3.x - 从子文件夹中的文件动态导入同名类
- gnuplot - 如何使用 Gnuplot 打印带有误差线和不同线点的 3D 图(splot)
- java - 如何使用 JUnit5 参数化测试 CSV 文件源?
- python - 如何在路径中使用变量?
- ckeditor - 使焦点在 CK Editor 5 createUIElement 中起作用
- android - Nativescript App - 在 Webview 中加载本地 HTML/JS/CSS
- kubernetes - (kubernetes/GKE) 如何根据客户端 IP 地址在 istio 中路由流量?
- swift - 在swift中,如何使用结构的唯一实例来实现tableView?