1. 任务
添加返回最顶端的按钮。
2. 实现
// 固定top按钮位置
<style>
/*返回顶部*/
#gotop{
position:fixed;
bottom:60px;
right:12px;
display:none;
}
</style>
<img src="images/go-to-top.png" id="gotop" alt="Top">
<!-- gotoTop-js -->
<script>
$(document).ready(function(){
$(function(){
// 下拉大于100px出现top按钮
$(window).scroll(function(){
if ($(window).scrollTop() > 100){
$("#gotop").fadeIn(100); //渐入动画
} else{
$("#gotop").fadeOut(100);
}
});
$('#gotop').click(function(){
$('body,html').animate( {
scrollTop : 0
}, 100);
});
});
});
</script>
效果:
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="device-width, initial-scale=1">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
<title>
Article!
</title>
<style>
/*返回顶部*/
#gotop{
position:fixed;
bottom:60px;
right:12px;
display:none;
}
</style>
<!-- <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> -->
<script src="js/jquery-3.5.1.js"></script>
</head>
<body>
<!-- <span name="gotop"></span> -->
<!-- 导航 -->
<nav>
<ul>
<li>首页</li>
<li>博客</li>
<li>图片</li>
</ul>
</nav>
<P align=center><STRONG>落花生</STRONG></P>
<P align=center>许地山</P>
<P>我们家的后园有半亩空地。母亲说:“让它荒着怪可惜的,你们那么爱吃花生,就开辟出来种花生吧。”我们姐弟几个都很高兴,买种、翻地、播种、浇水,没过几个月,居然收获了。</P>
<P>母亲说:“今晚我们过一个收获节,请你们的父亲也来尝尝我们的新花生,好不好?”母亲把花生做成了好几样食品,还咐附就在后园的茅亭里过这个节。</P>
<P>那晚上天色不大好。可父亲也来了,实在很难得。</P>
<P>父亲说:“你们爱吃花生吗?”</P>
<P>我们争着答应:“爱!”</P>
<P>“谁能把花生的好处说出来?”</P>
<P>姐姐说:“花生的味儿美。”</P>
<P>哥哥说:“花生可以榨油。”</P>
<P>我说:“花生的价钱便宜,谁都可以买来吃,都喜欢吃。这就是它的好处。”</P>
<P>父亲说:“花生的好处很多,有一样最可贵:它的果实埋在地里,不像桃子、石榴、苹果那样,把鲜红嫩绿的果实高高地挂在枝头上,使人一见就生爱慕之心。你们看它矮矮地长在地上,等到成熟了,也不能立刻分辨出来它有没有果实,也必须挖起来才知道。”</P>
<P>我们都说是,母亲也点点头。</P>
<P>父亲接下去说:“所以你们要像花生,它虽然不好看,可是很有用。”</P>
<P>我说:“那么,人要做有用的人,不要做只讲体面,而对人没有好处的人。”</P>
<P>父亲说:“对。这是我对你们的希望。”</P>
<P>我们谈到深夜才散。花生做的食品都吃完了,父亲的话深深地印在我的心上。</P>
<hr>
<!-- 底部 -->
<footer>
版权©rosefun.cn
</footer>
<!-- gotoTop -->
<img src="images/go-to-top.png" id="gotop" alt="Top">
<!-- gotoTop-js -->
<script>
$(document).ready(function(){
$(function(){
$(window).scroll(function(){
if ($(window).scrollTop() > 100){
$("#gotop").fadeIn(100); //渐入动画
} else{
$("#gotop").fadeOut(100);
}
});
$('#gotop').click(function(){
$('body,html').animate( {
scrollTop : 0
}, 100);
});
});
});
</script>
</body>
</html>
参考: