1、jquery的简易方法
$('a[href*="#"],area[href*="#"]').click(function() { if (location.pathname.replace(/^//, '') == this.pathname.replace(/^//, '') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']'); if ($target.length) { var targetOffset = $target.offset().top; $('html,body').animate({ scrollTop: targetOffset }, 1000); return false; } } });
2、原生javascript的简易方法
//取得a标签href里有#的属性
var a=document.getElementsByTagName("a");
var arr=[];
for(var i=0;i< a.length;i++){
if(a[i].href.indexOf("#")!=-1){
arr.push(a[i]);
}
}
//如果移动就停止滚动的方法
var bool=false;
var body=document.getElementsByTagName("body")[0];
body.addEventListener("mousewheel",function(){
bool=true;
});
//火狐的停止滚动
body.addEventListener("DOMMouseScroll",function(){
bool=true;
});
//为a标签href里有#的标签绑定事件
for(var i=0;i<arr.length;i++){
arr[i].onclick=function(){
bool=false;
if (location.pathname.replace(/^//, '') == this.pathname.replace(/^//, '') && location.hostname == this.hostname) {
var target=document.getElementsByName(this.hash.slice(1))[0];
var body=document.getElementsByTagName("body")[0];
if(target.offsetTop<body.scrollTop){
var timer=setInterval(function(){
var up_top=body.scrollTop;
body.scrollTop-=20;
if(body.scrollTop<=target.offsetTop||body.scrollTop==up_top||bool){
clearInterval(timer);
}
},1);
}else{
var timer=setInterval(function(){
var up_top=body.scrollTop;
body.scrollTop+=20;
if(body.scrollTop>=target.offsetTop||body.scrollTop==up_top||bool){
clearInterval(timer);
}
},1);
}
return false;
}
};
}