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


当前回答

旧的#top可以做到这一点

document.location.href = "#top";

适用于FF、IE和Chrome

其他回答

如果您想滚动到具有ID的任何元素,请尝试以下操作:

$('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 700, 'swing', function () {
        window.location.hash = target;
    });
});``

只需使用此脚本滚动到顶部直接。

<script>
$(document).ready(function(){
    $("button").click(function(){
        ($('body').scrollTop(0));
    });
});
</script>
document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });

你不需要JQuery。只需调用脚本

window.location = '#'

单击“转到顶部”按钮

示例演示:

输出.jsbin.com/fakumo#

PS:当你使用像angularjs这样的现代库时,不要使用这种方法。这可能会破坏URL散列。

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

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

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