jQuery練習t229,從0到1
阿新 • • 發佈:2021-02-05
技術標籤:jQueryJavaScriptjavascriptjquery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> body{ height: 1800px; } #box1,#box2{ display: inline-block; width: 100px; height: 100px; } #box1{ background-color: red; } #box2{ background-color: orange; position: fixed; } </style> <script src="../js/jquery-3.5.1.js"></script> <script> $(function () { //滾動事件 //固定欄目 //獲取box2距離頂部的距離 var top = $("#box2").offset().top; //根據滾動判斷定位 $(window).scroll(function () { if($(this).scrollTop() > top) { //當滾動條距離超過box2的位置時,設定為固定定位 $("#box2").css({ "position":"fixed", "top":"0" }); } else { //滾動條的距離小於box2的位置時,設定為相對定位 $("#box2").css({ "position":"relative", }); } }); }); </script> </head> <body> <div id="box1"></div><br> <div id="box2"></div> </body> </html>