代码改变世界

jquery插件--回到顶部的功能

2011-12-30 16:45  Komici  阅读(439)  评论(0编辑  收藏  举报
/*
* name: jquery.goTop.js
*
* Copyright (c) 2011
* $author: PoulXia$
* $Date: 2011-12-30$
* $Contact: xbh520@gmail.com$
*/

/**
* 一个基于jQuery的回到顶部功能的插件
* 调用示例1:
* $(document).ready(function () {
*     $.goTop({ renderTo: "middle2"});
* });
* 调用示例2:
* $(document).ready(function () {
*     $.goTop({renderTo:"divTop","top":"400px","right":"50px"});
* });
*/
; (function ($) {
    $.extend(
    {
        goTop: function (config) {
            //默认配置
            var goTopConfig ={"top":"350px","right":"50px"};

            for(var key in config){
                var val = config[key];
                if(val){
                    goTopConfig[key] = val;
                }
            }
            function checkScrollbar(el) {
                var top = $(document).scrollTop();
                if (top) {
                    el.show();
                } else {
                    el.hide();
                }
            }

            var el = $("#"+goTopConfig.renderTo);
            if(el.length < 1){
                alert("调用出错,请参考调用示例!");
                return false;
            }
            //默认样式
            el.css("position","fixed").css("top",goTopConfig.top).css("right",goTopConfig.right);

            //事件
            el.click(function () {
                $(document).scrollTop(0);
            });

            //检测是否显示
            checkScrollbar(el);

            $(window).scroll(function () {
                checkScrollbar(el);
            });
        }
    })
})(jQuery);

 

插件下载