(1)功能描述:
当滚动条向下滚动一定高度之后,变化某模块的定位使之转变为固定定位,而且随着浏览器窗口扩大缩小不改变位置,当滚动条位置小于一定高度时还原为之前定位方式。(类似天猫导航区域)
(2)实现代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{margin: 0px;padding: 0px;} body{padding-top: 150px;} #box{width: 780px;position: relative;margin: 0 auto;padding-left: 220px;} #box .left{width: 200px;height: 300px;background-color: orange;position: absolute;left: 0px;top: 0px;} #box .right{width: 780px;height: 1800px;background-color: #eee;} </style> <script src="jQuery-v1.8.3.js"></script> <script> $(function(){ $(window).resize(function(){ if ($(window).scrollTop()>155){ $(".left").css({"position":"fixed","left":$(".right").offset().left-220+"px","top":"0px"}); //这里-220是为了计算转换为固定定位后色块的left值跟之前一样 } else { $(".left").css({"position":"absolute","left":"0px","top":"0px"}); } }); $(window).scroll(function(){ if ($(window).scrollTop()>155){ $(".left").css({"position":"fixed","left":$(".right").offset().left-220+"px","top":"0px"}); } else { $(".left").css({"position":"absolute","left":"0px","top":"0px"}); } }); }) </script> </head> <body> <hr /> <div id="box"> <div class="left"></div> <div class="right"></div> </div> </body> </html>