<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
.backtop{
position: fixed;
right: 40px;
bottom: 50px;
display: none;
}
div{
height: 500px;
border: 1px solid red;
}
</style>
<body>
<img src="img/01.png" alt="" class="backtop" />
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
<script src="js/jquery-1.7.2.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$('.backtop').hover(function(){
$(this).attr('src','img/05.gif');
},function(){
$(this).attr('src','img/01.png');
});
$(window).scroll(function(){
var _top = $(this).scrollTop();
if(_top > 200){
$('.backtop').fadeIn(200);
}else{
$('.backtop').fadeOut(200);
}
console.log(_top)
});
$('.backtop').click(function(){
$('html,body').animate({
scrollTop:0
},500,function(){
alert('ok');
});
});
</script>
</html>
或者使用下面代碼javascript
//一鍵置頂 | |
$(window).scroll(function(){ | |
var win_top = $(window).scrollTop(); | |
if(win_top > 0){ | |
$('.tips .backtop').fadeIn(100); | |
}else{ | |
$('.tips .backtop').fadeOut(100); | |
} | |
}); | |
$('.backtop').bind('click', function(){ | |
$('html,body').animate({scrollTop: '0px'}, 300); | |
}); |