<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body{ padding: 0; margin: 0; } .fixed { position: fixed; top: 0; 100%; transition: .3s; } </style> </head> <body> <div style="height: 1500px;position: relative;"> <div style="height: 80px;"></div> <div id="head" style="height: 120px;background-color: #000;"></div> </div> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> $(document).scroll(function () { if ($(window).scrollTop() >= 80) { if (!$("#head").hasClass("fixed")) { $("#head").addClass("fixed") } } else if ($("#head").hasClass("fixed")){ $("#head").removeClass("fixed") } }); </script> </body> </html>
参考:
https://www.cnblogs.com/zhaoyingjie/p/6088358.html
https://www.w3school.com.cn/jquery/attributes_removeclass.asp
https://www.jb51.net/article/146887.htm
https://blog.csdn.net/qq_29207823/article/details/81565160