jQuery实现回到顶部的功能

回到顶部的功能在网页中很常见。当网站内容过多的时候,添加一个返回顶部的功能,可以更好的增加用户体验。
今天动手用jQuery写了这样一个效果。但是还有有一个问题:当点击回到顶部按钮时,滚轮回滚的时候,无法实现。
如果有朋友知道解决方案,麻烦指点下下。

但是IE6不支持fixed属性。在这里做了一下兼容.

*{margin:0;padding:0;}
/*测试,浏览器产生滚动条*/
body{height:2000px;}
/*解决IE6下固定定位抖动的问题*/
*html,*html body{
	background-image: url(about:blank);
	background-attachment: fixed;
}
#back{
	width:55px;
	height:55px;
	/*开始是隐藏的*/
	display: none;
	background:url(back.png) no-repeat -70px 0;
	position:fixed;
	right:30px;
	bottom:30px;
	/*兼容IE6*/
	_position:absolute;
	_right:30px;
	/*
		可视区域的高度-自身的高度-距离底部的距离+滚动的距离
	*/
	_top:expression(eval(document.documentElement.clientHeight-this.offsetHeight-30+document.documentElement.scrollTop));
}

简单说下步骤:

  • 隐藏回到顶部按钮
  • 滚动条滚动一定距离后显示按钮,一般都是可视区域的高度
  • 点击按钮回到顶部

具体的写法如下:

$(function(){
	//获取元素
	var $goBack = $('#back');
	$goBack.click(function(){
		var $body = (window.opera) ? (document.compatMode == 'CSS1Compat' ? $('html') : $('body')) : $('html,body');
		$body.animate({
			scrollTop:0
		}, 1000);
	});
	$goBack.hover(function(){
		$(this).css('background',  'url(back.png) no-repeat 0 0');
	}, function(){
		$(this).css('background', 'url(back.png) no-repeat -70px 0');
	});
	$(window).scroll(function(e){
		//当滚到的高度超过浏览器可视区域的高度
		if($(window).scrollTop() > $(window).height()){
			$goBack.fadeIn(1000);
		}else{
			$goBack.fadeOut(1000);
		}
	});
});

这个版本不是最好的,只是简单的实现了下下。希望各位大家指点下下。

posted @ 2015-01-14 22:32  BetterMapleme  阅读(1032)  评论(0编辑  收藏  举报