利用偏移量offset()和动画animate实现点击移动效果

    1. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    2. <style>
    3. body{
    4. height: 2500px;
    5. }
    6. .head{
    7. top:0;
    8. left:0;
    9. height: 50px;
    10. position: fixed;
    11. }
    12. div{
    13. width:100px;
    14. height: 100px;
    15. background-color: red;
    16. }
    17. #html{
    18. margin-top: 500px;
    19. }
    20. #css{
    21. margin-top: 500px;
    22. }
    23. #js{
    24. margin-top: 500px;
    25. }
    26. </style>
    27. </head>
    28. <body>
    29. <p class="head">
    30. <a href="#html">html</a>
    31. <a href="#css">css</a>
    32. <a href="#js">javascript</a>
    33. </p>
    34. <div id="html">
    35. html
    36. </div>
    37. <div id="css">
    38. css
    39. </div>
    40. <div id="js">
    41. javascript
    42. </div>
    43. <script>
    44. /*
    45. $(element).attr(value)
    46. */
    47. $(".head a").click(function(){
    48. var id = $(this).attr("href");
    49. var offsetTop = $(id).offset().top;
    50. console.log(offsetTop)
    51. $("html,body").animate({scrollTop:offsetTop})
    52. return false;
    53. })
    54. </script>