阻止连接默认跳转,利用监听事件参数 e,并调用函数preventDefault()
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title></title>
<style type="text/css">
a{
display: block;
width: 40px;
height: 40px;
background-color: blue;
position: fixed;
right: 10px;
bottom: 0px;
}
p{
height: 500px;
}
</style>
</head>
<body>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<a href="" id="ha">连接</a>
<script>
var timer=null;
var d=document.getElementById("ha");
d.addEventListener("click",function(e){
e.preventDefault(); //阻止默认行为,在这里可以阻止连接的默认跳转
timer=setInterval("back()",20);//设置定时器,每20ms执行一次back函数
},false);
function back(){
if(document.body.scrollTop==0){ //当滚动条回到顶部,清除定时器。
clearInterval(timer);
}else{
document.body.scrollTop-=300;
}
}
</script>
</body>
</html>
阻止默认跳转的另一种方式 href='javascript:;'
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title></title>
<style type="text/css">
a{
display: block;
width: 40px;
height: 40px;
background-color: blue;
position: fixed;
right: 10px;
bottom: 0px;
}
p{
height: 500px;
}
</style>
</head>
<body>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<p>aaaaaaaaaaaaaaaaaaaaaaa</p>
<a href="javascript:;" id="ha">连接</a> <!--javascript:; 执行一段空代码,即什么也不做,连接不会跳转-->
<script>
var timer=null;
var d=document.getElementById("ha");
d.addEventListener("click",function(e){
//e.preventDefault();
timer=setInterval("back()",20);//设置定时器,每20ms执行一次back函数
},false);
function back(){
if(document.body.scrollTop==0){ //当滚动条回到顶部,清除定时器。
clearInterval(timer);
}else{
document.body.scrollTop-=300;
}
}
</script>
</body>
</html>
补充:
javascript:; 表示什么都不执行,这样点击<a>时就没有任何反应。跟href="javascript:void(0)"是一样