【代码片段】jquery 回到顶部效果(全兼容浏览器)可自定义出现位置和页面宽度

演示地址:http://www.wufangbo.com/demo/jquery/21/index.html

下载地址:http://www.wufangbo.com/demo/jquery/21/21.rar

js代码 不要忘记先调取jqury

<script type=”text/javascript”>
//返回顶部
(function($){
var goToTopTime;
$.fn.goToTop=function(options){
var opts = $.extend({},$.fn.goToTop.def,options);
var $window=$(window);
$body = (window.opera) ? (document.compatMode == “CSS1Compat” ? $(‘html’) : $(‘body’)) : $(‘html,body’); // opera fix
//$(this).hide();
var $this=$(this);
clearTimeout(goToTopTime);
goToTopTime=setTimeout(function(){
var controlLeft;
if ($window.width() > opts.pageHeightJg * 2 + opts.pageWidth) {
controlLeft = ($window.width() – opts.pageWidth) / 2 + opts.pageWidth + opts.pageWidthJg;
}else{
controlLeft = $window.width()- opts.pageWidthJg-$this.width();
}
var cssfixedsupport=$.browser.msie && parseFloat($.browser.version) < 7;//判断是否ie6
var controlTop=$window.height() – $this.height()-opts.pageHeightJg;
controlTop=cssfixedsupport ? $window.scrollTop() + controlTop : controlTop;
var shouldvisible=( $window.scrollTop() >= opts.startline )? true : false;

if (shouldvisible){
$this.stop().show();
}else{
$this.stop().hide();
}

$this.css({
position: cssfixedsupport ? ‘absolute’ : ‘fixed’,
top: controlTop,
left: controlLeft
});
},30);

$(this).click(function(event){
$body.stop().animate( { scrollTop: $(opts.targetObg).offset().top}, opts.duration);
$(this).blur();
event.preventDefault();
event.stopPropagation();
});
};

$.fn.goToTop.def={
pageWidth:960,//页面宽度
pageWidthJg:5,//按钮和页面的间隔距离
pageHeightJg:120,//按钮和页面底部的间隔距离
startline:30,//出现回到顶部按钮的滚动条scrollTop距离
duration:200,//回到顶部的速度时间
targetObg:”body”//目标位置
};
})(jQuery);
$(function(){
$(‘<a href=”javascript:;” class=”backToTop”>返回顶部</a>’).appendTo(“body”);
});
//调用返回顶部
$(function(){
$(“.backToTop”).goToTop({});
$(window).bind(‘scroll resize’,function(){
$(“.backToTop”).goToTop({});
});
});
</script>

css代码

.backToTop {width:47px; height:47px; display:block; text-align:center; background:#999; color:#fff;cursor:pointer; font-size:12px;}

来源:http://www.wufangbo.com

posted @ 2012-11-05 15:54  KOJYA  阅读(401)  评论(0编辑  收藏  举报