代码改变世界

JS仿淘宝详情页菜单条智能定位效果

2014-01-15 15:40  龙恩0707  阅读(4057)  评论(9编辑  收藏  举报

    类似于淘宝详情页菜单条智能定位 对于每个人来说并不陌生!如下截图所示:红色框的那部分!

   

基本原理:

       是用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下载