做过手机版的效果,PC也同时有效,代码是收集来的,不够精简,但可用。效果如下:
("#first")为需要浮动的DIV
<script type="text/javascript" src="js/jquery.min.js"></script> <script> $.fn.smartFloat = function() { var position = function(element) { var top = element.position().top, pos = element.css("position"); var browser=navigator.appName; var browser2=navigator.userAgent; $(window).scroll(function() { var scrolls = $(this).scrollTop(); if (scrolls > 120) { if (window.XMLHttpRequest) { if(browser2.indexOf("Chrome") > -1 || browser2.indexOf("MSIE")> -1 || browser2.indexOf("iPhone")> -1){ element.css({position: "fixed",top: 0});//更改这里的0可以设定在哪个Y位置固定 }else{ element.css({position: "fixed",top: scrolls}); } } else { element.css({top: scrolls}); } }else { element.css({position: pos,top: top}); } }); }; return $(this).each(function() { position($(this)); }); }; $("#first").smartFloat(); </script>