首页 > 解决方案 > 使用 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,但没有比较这两种方法的信息。

标签: javascriptreactjs

解决方案


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>


推荐阅读