tags: ‘js’

categories: ‘js’

JS自动滚动到底部 scrollTop

  1. var div = document.getElementById(’id‘);
  2. div.scrollTop = div.scrollHeight

滚动到指定的位置 element.scrollIntoView()

  • 参数 默认true, false
    • true: 页面(或容器)发生滚动,使element的顶部与视图(容器)顶部对齐;
    • false: 使element的底部与视图(容器)底部对齐。
      PS:页面(容器)可滚动时才有用!
  1. document.getElementById('id').scrollIntoView(true);

滚动到顶部 window.scrollBy window.scrollTo

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. <style>
  7. .box{
  8. position: fixed;
  9. left:20px;
  10. bottom:20px;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div class="box">
  16. <button onclick="window.scrollTo(100,100)">直接回到距离左100,上100的地方</button>
  17. <button onclick="window.scrollBy(-10,-10)">每次以 10 向左,向上移动</button>
  18. <button onclick="toTop()">缓慢回到顶部</button>
  19. </div>
  20. <div>
  21. <p style="font-size: 100px;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veritatis, quis aut et consequuntur alias optio dolorum ullam sequi quos nulla eum voluptas tempore quisquam impedit modi commodi atque porro ratione.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veritatis, quis aut et consequuntur alias optio dolorum ullam sequi quos nulla eum voluptas tempore quisquam impedit modi commodi atque porro ratione.</p>
  22. </div>
  23. <script>
  24. function toTop(){
  25. var timer = setInterval(function (){
  26. var t = document.body.scrollTop || document.documentElement.scrollTop;
  27. if(t <= 0){
  28. clearInterval(timer);
  29. return;
  30. }
  31. window.scrollBy(0,-50); // 左不移动,每次以 50 向上移动
  32. // window.scrollBy(-10,-10); // 每次以 10 向左,向上移动
  33. },20);
  34. }
  35. </script>
  36. </body>
  37. </html>