JS仿淘寶詳情頁菜單條智能定位效果


    類似於淘寶詳情頁菜單條智能定位 對於每個人來說並不陌生!如下截圖所示:紅色框的那部分!

   

基本原理:

       是用JS偵聽滾動事件,當頁面的滾動距離(頁面滾動的高度)大於或者等於 "對象"(要滾動的對象)距離頁面頂部的高度,也就是說滾動的對象與窗口的上邊緣接觸時,立即將對象定位屬性position值改成fixed(固定)(除IE6以外,因為IE6不支持fixed)。對於IE6用絕對定位position:absolute,top:就是"游覽器滾動的top"。在IE6下瀏覽看到會有小抖動,不過目前也沒有辦法的,淘寶詳情頁貌似也是這樣處理的!

JSFiddle效果如下:

  想要查看效果 請點擊我!

代碼比較簡單! 不多說!直接貼代碼:

HTML如下:

<div class="container">
    <div style="height:300px;">我是來占位的,不要煩我啊!</div>
    <div id = "nav" class="nav">
        <ul>
            <li><a href="#">寶貝詳情</a></li>
            <li class="current"><a href="#">評價詳情(200)</a></li>
            <li><a href="#">成交記錄(20000)</a></li>
        </ul>
    </div>
        <div style="height:1800px;"></div>
</div>

css代碼如下:

.container{width:720px;margin:0 auto;}
* {margin:0;padding:0;}
ol,ul{list-style:none}
 .nav {width:720px;height:42px;position:absolute;margin:0 auto;border:1px solid #d3d3d3; background:#f7f7f7;-moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px;}
 .nav li{float:left;height:42px;line-height:42px;padding:0 10px;border-right: 1px solid #d3d3d3; font-size:14px; font-weight:bold}
     
 .nav li.current{background:#f1f1f1; border-top:1px solid #f60} 

.nav li a{text-decoration:none;} 
.nav li.current a{color:#333} 
.nav li a:hover{color:#f30} 

JS代碼如下:

/**
 * JS仿淘寶詳情頁菜單條智能定位效果
 * constructor SmartFloat 
 * @author tugenhua
 * @time 2014-1-15
 */

 function SmartFloat(options) {
     
     this.config = {
        targetElem   :  '#nav'  // 要定位的dom節點
     };

     this.cache = {};

     this.init(options);
 }

 SmartFloat.prototype = {
    
    constructor: SmartFloat,

    init: function(options){
        this.config = $.extend(this.config, options || {});
        var self = this,
            _config = self.config,
            _cache = self.cache;
        
        var top = $(_config.targetElem).offset().top,
            pos = $(_config.targetElem).css('position'),
            isIE6 = navigator.userAgent.match(/MSIE 6.0/)!= null;

        $(window).scroll(function(){
            var winTop = $(this).scrollTop();
            if(winTop >= top) {
                
                if(!isIE6) {
                    $(_config.targetElem).css({
                        position: 'fixed',
                        top: 0
                    });
                }else {
                    $(_config.targetElem).css({
                        position: 'absolute',
                        top: winTop
                    });
                }
            }else {
                $(_config.targetElem).css({
                    position: pos,
                    top: top
                });
            }
        });
    }
 };

 // 頁面初始化

 $(function(){
     new SmartFloat({
     
     });
 });
View Code

demo下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM