1. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    2. <style>
    3. .container>div{
    4. height: 400px;
    5. margin-top: 40px;
    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: #eee;;
    23. top:0;
    24. }
    25. </style>
    1. <div class="nav">
    2. <a href="#html">html</a>
    3. <a href="#css">css</a>
    4. <a href="#js">javascript</a>
    5. <a href="#vue">vue</a>
    6. </div>
    7. <div class="container">
    8. <div id="html">html</div>
    9. <div id="css">css</div>
    10. <div id="js">javascript</div>
    11. <div id="vue">vue</div>
    12. </div>
    13. <script>
    14. /* obj.offset().top 获取元素距离顶部的距离
    15. attr(param) 获取元素的属性
    16. $('html,body').animate({scrollTop:params})
    17. */
    18. $(".nav a").click(function(){
    19. /* 1.获取当前元素对应跳转的元素距离顶部的高度 */
    20. var attr = $(this).attr("href");
    21. var top = $(attr).offset().top;
    22. console.log(attr)
    23. console.log(top)
    24. /* 2.让窗口滚动对应的高度 */
    25. $("html,body").animate({scrollTop:top})
    26. return false;
    27. })
    28. </script>