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


当前回答

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

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

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

其他回答

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

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

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

使用window.scrowlTo(0,0);速度非常快所以我尝试了Mark Ursino的例子,但在Chrome中什么都没有发生我找到了这个

$('.showPeriodMsgPopup').click(function(){
    //window.scrollTo(0, 0);
    $('html').animate({scrollTop:0}, 'slow');//IE, FF
    $('body').animate({scrollTop:0}, 'slow');//chrome, don't know if Safari works
    $('.popupPeriod').fadeIn(1000, function(){
        setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
    });
});

测试了所有3种浏览器,并正常工作我正在使用蓝图css这是当客户点击“立即预订”按钮并且没有选择租赁期时,慢慢移动到日历所在的顶部,并打开一个指向2个字段的对话框div,3秒后它会消失

$(“.solltop”).click(函数){$(“html,body”).animate({scrollTop:0},“slow”);return false;});.节{高度:400px;}.第1节{背景色:#333;}.第2节{背景色:红色;}.第3节{背景色:黄色;}.第4节{背景色:绿色;}.滚动条{位置:固定;右:10px;底部:10px;颜色:#fff;}<html><head><title>滚动顶部演示</title><script src=“https://code.jquery.com/jquery-3.3.1.js“></script></head><body><div class=“content wrapper”><div class=“section section1”></div><div class=“section section2”></div><div class=“section section3”></div><div class=“section section4”></div>滚动顶部</a></div></body></html>

<script>
$(function(){
   var scroll_pos=(0);          
   $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>

编辑:

$('html, body').animate({scrollTop:(scroll_pos)}, 2000);

另一种上下边距滚动方式:

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

您可以简单地使用链接中的目标,例如#someid,其中#someid是div的id。

或者,您可以使用任何数量的滚动插件,使其更加优雅。

http://plugins.jquery.com/project/ScrollTo是一个例子。