查看文章
 
jquery实现返回顶部的滑动效果
2009-01-27 15:12

以前返回顶部,直接<a href="#">返回顶部</a>,效果是实现了,可是却是“嘣”得一下跳到最上面,胆小的可能会被吓一跳,这样的交互是不友好的。要是单击“返回顶部”后页面会慢慢的滚动到最顶端,岂不是很好?ok,下面这段代码就是实现这样的效果的,不用客气,直接copy过去——

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>返回顶部</title>
<style type="text/css">
.box{width:600px; height:1000px;}
a{text-decoration:none; color:#ff0200; font-size:14px; background:#CCCCCC; width:95%; display:block; text-align:right; padding-right:20px;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
</head>

<body>
<div class="box"></div>
<a href="#content">Back to top &uarr;</a>
<script type="text/javascript">
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$('html, body').animate({scrollTop: targetOffset}, 900, function() {
location.hash = target;
});
});
}
}
});
});
</script>
</body>
</html>

使用说明:以上代码直接复制到HTML页面中,运行预览,滚动条滚动到底部,会看见“Back to top ↑”字样,单击,你会看到页面慢慢上升,呵呵,效果不错哦~~

注意,如果你没有效果,看看你是否联网了,是否可以上国外的网站,如果上述条件不符合,看不到效果哦。

a标签中的href="#content"你可以改动,什么href="#sb",href="#nb"都行,demo(但是)href="#"不行哦,它会“嘣”地一下跳到到上面。

(完)


类别:web前端||添加到搜藏 |分享到i贴吧|浏览(1263)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu