滚动页面到一定位置时显示回到顶部按钮

当页面比较长时,如果滚动到一定位置想回到顶部会比较麻烦,所以页面上会适时的出现“回到顶部”按钮,以显示图片为例。
代码如下:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
		div{
      
      
			height: 1500px;
			width: 100%;
		}
		img{
      
      
			position: fixed;
			right: 20px;
			bottom: 50px;
			cursor: pointer;
		}
	</style>
	<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
</head>
<body>
	<div></div>
	<img src="ad-01.jpg">
	
</body>
<script type="text/javascript">
	$("img").hide();//隐藏
	$(window).scroll(function(){
      
      
		if($(window).scrollTop()>150){
      
      
			$("img").fadeIn();//淡入效果
		}else{
      
      
			$("img").fadeOut();//淡出效果
		}
	})
	$("img").click(function(){
      
      
		$("html,body").animate({
      
      scrollTop:0},400);
	})
</script>
</html>

这个中间使用了jQuery,版本是jquery-1.11.1.min.js,其他版本不确定是不是都可以,可以试试。

猜你喜欢

转载自blog.csdn.net/jasmyn518/article/details/121866045