首页 >web前端 >js教程 >随窗体滑动的小插件sticky源码_javascript技巧

随窗体滑动的小插件sticky源码_javascript技巧

WBOY
WBOY原创
2016-05-16 17:31:49976浏览

复制代码 代码如下:

     $.fn.stickyfloat = function(options, lockBottom) {
                var $obj                 = this;
                var parentPaddingTop     = parseInt($obj.parent().css('padding-top'));
                var startOffset         = $obj.parent().offset().top;
                var opts                 = $.extend({ startOffset: startOffset, offsetY: parentPaddingTop, duration: 200, lockBottom:true }, options);

                $obj.css({ position: 'absolute' });

                if(opts.lockBottom){
                    var bottomPos = $obj.parent().height() - $obj.height() + parentPaddingTop;
                    if( bottomPos                         bottomPos = 0;
                }

                $(window).scroll(function () {
                    $obj.stop();

                    var pastStartOffset            = $(document).scrollTop() > opts.startOffset;  
                    var objFartherThanTopPos    = $obj.offset().top > startOffset;  
                    var objBiggerThanWindow     = $obj.outerHeight()

                    if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){
                        var newpos = ($(document).scrollTop() -startOffset + opts.offsetY );
                        if ( newpos > bottomPos )
                            newpos = bottomPos;
                        if ( $(document).scrollTop()                             newpos = parentPaddingTop;

                        $obj.animate({ top: newpos }, opts.duration );
                    }
                });
            };


使用方法很简单:只要在页面中引入该插件,然后用选择器调用:
复制代码 代码如下:

$('#menu15').stickyfloat({ duration: 500 });
$('#menu14').stickyfloat({ duration: 500 });
$('#menu13').stickyfloat({ duration: 500 });
$('#menu12').stickyfloat({ duration: 500 });

  后面的duration参数表示滑动的速度,越大越慢。
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn