1 // JavaScript Document 2 (function($){ 3 var goToTopTime; 4 $.fn.goToTop=function(options){ 5 var opts = $.extend({},$.fn.goToTop.def,options); 6 var $window=$(window); 7 $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); // opera fix 8 $(this).hide(); 9 var $this=$(this); 10 clearTimeout(goToTopTime); 11 goToTopTime=setTimeout(function(){ 12 var controlLeft; 13 if ($window.width() > opts.pageHeightJg * 2 + opts.pageWidth) { 14 controlLeft = ($window.width() - opts.pageWidth) / 2 + opts.pageWidth + opts.pageWidthJg; 15 }else{ 16 controlLeft = $window.width()- opts.pageWidthJg-$this.width(); 17 } 18 var cssfixedsupport=$.browser.msie && parseFloat($.browser.version) < 7;//判断是否ie6 19 var controlTop=$window.height() - $this.height()-opts.pageHeightJg; 20 controlTop=cssfixedsupport ? $window.scrollTop() + controlTop : controlTop; 21 var shouldvisible=( $window.scrollTop() >= opts.startline )? true : false; 22 23 if (shouldvisible){ 24 $this.stop().show(opts.showBtntime); 25 }else{ 26 $this.stop().hide(opts.showBtntime); 27 } 28 29 $this.css({ 30 position: cssfixedsupport ? 'absolute' : 'fixed', 31 top: controlTop, 32 left: controlLeft 33 }); 34 },500); 35 36 $(this).click(function(event){ 37 $body.stop().animate( { scrollTop: $(opts.targetObg).offset().top}, opts.duration); 38 $(this).blur(); 39 event.preventDefault(); 40 event.stopPropagation(); 41 }); 42 }; 43 44 $.fn.goToTop.def={ 45 pageWidth:950,//页面宽度 46 pageWidthJg:10,//按钮和页面的间隔距离 47 pageHeightJg:50,//按钮和页面底部的间隔距离 48 startline:20,//出现回到顶部按钮的滚动条scrollTop距离 49 duration:200,//回到顶部的速度时间 50 showBtntime:100,//显示\隐藏回到顶部按钮的速度时间 51 targetObg:"body"//目标位置 52 }; 53 })(jQuery); 54 $(function(){ 55 $('<a href="#" class="go-top"><img src="themes/cyjy/images/go-top.png" alt="" /></a>').appendTo("body"); 56 });
注意第18行变量cssfixedsupport,该插件完美支持IE6下有不支持position:fixed的bug.
var cssfixedsupport=$.browser.msie && parseFloat($.browser.version) < 7;//判断是否ie6 var controlTop=$window.height() - $this.height()-opts.pageHeightJg; controlTop=cssfixedsupport ? $window.scrollTop() + controlTop : controlTop;
如在IE6下就用absolute进行布局,这样在鼠标滚动时要通过$window.scrollTop()获取滚动条到顶部的垂直高度来修正controlTop参数。
通过触发鼠标单击事件回到顶部!