查看: 39|回复: 0

[JavaScript/JQuery] js滚动到指定元素

发表于 2018-4-7 08:00:00
代码:
  1. <style>
  2. button{
  3. position: fixed;
  4. bottom: 0;
  5. right: 0;
  6. }
  7. </style>
  8. <button id="button">click to see</button>
  9. <p>1</p>
  10. <p>1</p>
  11. <p>1</p>
  12. <p>1</p>
  13. <p>1</p>
  14. <p>1</p>
  15. <p>1</p>
  16. <p>1</p>
  17. <p>1</p>
  18. <p>1</p>
  19. <p>1</p>
  20. <p>1</p>
  21. <p>2</p>
  22. <p>1</p>
  23. <p>1</p>
  24. <p>1</p>
  25. <p>1</p>
  26. <p>1</p>
  27. <p>1</p>
  28. <p>1</p>
  29. <p>1</p>
  30. <p>3</p>
  31. <p>1</p>
  32. <p>1</p>
  33. <p>1</p>
  34. <p>1</p>
  35. <p>1</p>
  36. <p>1</p>
  37. <p>1</p>
  38. <p>1</p>
  39. <a id="ele" href="#">see me</a>
  40. <p>1</p>
  41. <p>1</p>
  42. <p>1</p>
  43. <p>1</p>
  44. <p>1</p>
  45. <p>1</p>
  46. <p>1</p>
  47. <p>1</p>
  48. <p>1</p>
  49. <p>1</p>
  50. <p>1</p>
  51. <p>3</p>
  52. <p>1</p>
  53. <p>1</p>
  54. <p>1</p>
  55. <p>1</p>
  56. <p>1</p>
  57. <p>1</p>
  58. <p>1</p>
  59. <p>1</p>
  60. <p>1</p>
  61. <p>1</p>
  62. <p>1</p>
  63. <p>4</p>
  64. <p>1</p>
  65. <p>1</p>
  66. <script>
  67. var button = document.getElementsByTagName('button')[0]
  68. button.onclick = function(){
  69. clickToSee('ele')
  70. }
  71. function clickToSee(id,time = 1){
  72. var c_top = document.body.scrollTop
  73. var ele = document.getElementById(id)
  74. var e_top = ele.offsetTop
  75. var diff = e_top - c_top
  76. var step = diff/100
  77. time = time/100*1000
  78. var o_flag
  79. if(diff>0){
  80. o_flag = true
  81. }else{
  82. o_flag = false
  83. }
  84. var timer = setInterval(function(){
  85. var c_flag
  86. diff -= step
  87. window.scrollBy(0,step)
  88. if(diff>0){
  89. c_flag = true
  90. }else{
  91. c_flag = false
  92. }
  93. if(!o_flag === c_flag){
  94. clearInterval(timer)
  95. }
  96. console.log(diff)
  97. },time)
  98. }
  99. </script>
复制代码
效果:
js滚动到指定元素
js滚动到指定元素
js滚动到指定元素


回复

使用道具 举报