如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。


当前回答

用于滚动到页面顶部的元素和元素

WebElement tempElement=driver.findElement(By.cssSelector("input[value='Excel']"));

            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", tempElement);

其他回答

滚动到带有动画的页面顶部:

window.scrollTo({ top: 0, behavior: 'smooth' });

旧的#top可以做到这一点

document.location.href = "#top";

适用于FF、IE和Chrome

TypeScript中的等效解决方案可能如下

   window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });

如果您确实想要平滑滚动,请尝试以下操作:

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。

纯JavaScript解决方案:

function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
});

我在Codepen上编写了一个动画解决方案

此外,您可以尝试使用CSS滚动行为的另一种解决方案:smooth属性。

html {
    scroll-behavior: smooth;
}

@media (prefers-reduced-motion: reduce) {
    html {
        scroll-behavior: auto;
    }
}