1. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    2. <style>
    3. .container>div{
    4. height: 300px;
    5. margin-top: 50px;
    6. }
    7. .container>div:nth-child(1){
    8. background: red;
    9. }
    10. .container>div:nth-child(2){
    11. background: blue;
    12. }
    13. .container>div:nth-child(3){
    14. background: yellow;
    15. }
    16. .container>div:nth-child(4){
    17. background: green;
    18. }
    19. .nav{
    20. position: fixed;
    21. line-height: 50px;
    22. background: rgb(50, 166, 233);
    23. top: 0;
    24. }
    25. </style>
    26. </head>
    27. <body>
    28. <div class="nav">
    29. <a href="#html">html</a>
    30. <a href="#css">css</a>
    31. <a href="#javascript">javascript</a>
    32. <a href="#vue">vue</a>
    33. </div>
    34. <div class="container">
    35. <div id="html">html</div>
    36. <div id="css">css</div>
    37. <div id="javascript">javascript</div>
    38. <div id="vue">vue</div>
    39. </div>
    40. <script>
    41. /* obj.offset().top 获取元素距离顶部的距离
    42. attr(param) 获取元素的属性
    43. $("html,body").animate({scrollTop:param})
    44. */
    45. $(".nav a").click(function(){
    46. /* 1.获取当前元素对应跳转的元素距离顶部的高度 */
    47. var attr = $(this).attr("href");
    48. var top = $(attr).offset().top;
    49. console.log(attr)
    50. console.log(top)
    51. /* 2.让窗口滚动对应的高度 */
    52. $("html,body").animate({scrollTop:top})
    53. return false;
    54. })
    55. </script>