前言
最近要设计一个网页,想实现一个类似于菜鸟教程的返回顶部按钮,但找了很久都没找着合适的实现方法,最后自己结合菜鸟教程的设置和网上的其他一些设置,自己结合jQuery实现了这个功能。
希望能对你有所帮助。
效果图
点击右下角的小方块可以返回网页顶部
实现
- 首先设置一个贴附在网页右下角的div小块的css
<style>
.fixed-btn {
position: fixed;
right: 1%;
bottom: 5%;
width: 40px;
border: 1px solid #eee;
background-color: white; /*背景颜色,可自己更改*/
font-size: 24px;
z-index: 1040;
}
</style>
- 设置一个放在放在上面那个div里的a元素的css
#btn_top {
text-decoration:none; /*取消连接的下划线*/
/*使这个zhana元素称为块级元素,并使他能够占满div*/
display:block;
height:100%;
width:100%;
}
- 然后再用jQuery实现功能
<script>
$(function () {
$('.fixed-btn').hide(); //先让回顶部的div隐藏
$(window).scroll(function () {
//当网页滑下一定距离时使返回顶部的div出现
if ($(window).scrollTop() >= 200) {
$('.fixed-btn').fadeIn();
}
else {
$('.fixed-btn').fadeOut();
}
});
});
//这里是使ID为btn_top的可点击元素实现回到顶部的点击事件
$('#btn_top').click(function () {
$('html,body').animate({ scrollTop: 0 }, 500);
});
</script>
完整的style和body部分HTML代码
<style>
.fixed-btn {
position: fixed;
right: 1%;
bottom: 5%;
width: 40px;
border: 1px solid #eee;
background-color: white;
font-size: 24px;
z-index: 1040;
}
#btn_top {
text-decoration:none;
height:100%;
width:100%;
display:block;
}
</style>
<body>
<!--网页内容-->
<!--返回顶部-->
<div class="fixed-btn text-center">
<a id="btn_top" href="javascript:void(0)"> ↑</a>
</div>
<script>
$(function () {
$('.fixed-btn').hide();
$(window).scroll(function () {
if ($(window).scrollTop() >= 200) {
$('.fixed-btn').fadeIn();
}
else {
$('.fixed-btn').fadeOut();
}
});
});
$('#btn_top').click(function () {
$('html,body').animate({ scrollTop: 0 }, 500);
});
</script>
</body>