如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
平滑滚动,纯javascript:
(function smoothscroll(){
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo (0,currentScroll - (currentScroll/5));
}
})();
其他回答
纯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;
}
}
尝试此操作以在顶部滚动
<script>
$(document).ready(function(){
$(window).scrollTop(0);
});
</script>
请检查以下代码,这肯定会有帮助。:)
document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.
用于滚动到页面顶部的元素和元素
WebElement tempElement=driver.findElement(By.cssSelector("input[value='Excel']"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", tempElement);
您可以使用javascript的内置函数scrollTo:
函数滚动(){window.scrollTo({顶部:0,行为:“平滑”});}<button onclick=“scroll”>滚动</button>