<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script src="../jquery-3.3.1.js"></script> <style> *{ margin: 0; padding: 0; } img{ display: block; } .main{ width: 1000px; margin: 0 auto; } </style> <script> $(function () { var h = $(".top").height(); $(window).scroll(function () { if($(document).scrollTop()>h){ $(".nav").css({"position":"fixed","top":0}); }else{ $(".nav").css({"position":"static"}); //static(静态定位):默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。 } }) }) </script> </head> <body> <div class="top"> <img src="top.png" alt=""/> </div> <div class="nav"> <img src="nav.png" alt=""/> </div> <div class="main"> <img src="main.png" alt=""/> </div> </body> </html>
图片: