最近用到了返回顶部和底部功能,找了找,查了查,改了改,最终实现效果大概这样子。
以下是相关代码:
html部分:
<div id="backtotop" class="backtotop">
<div class="bt-box gotop" title="返回顶部"><i class="iconfont icon-up"></i></div>
<div class="bt-box gobottom" title="返回文末"><i class="iconfont icon-under"></i></div>
</div>
CSS样式,引入对应的字体图标样式(上下箭头符号),或者自己用图标替换:
@font-face {
font-family: "iconfont"; /* Project id */
src: url('/image/iconfont.ttf') format('truetype');
}
.backtotop {
z-index: 999;
bottom: 70px;
position: fixed;
right: 2%;
cursor: pointer;
transform: translate3d(0,0,0);
}
.backtotop .bt-box {
margin-bottom: 4px;
width: 50px;
height: 32px;
line-height: 32px;
vertical-align: middle;
background: rgb(68,142,246);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border-radius: 10px;
box-shadow: 0 1px 1px rgba(0,0,0,0.04);
text-align: center;
}
.backtotop i {
color: #fff;
}
.backtotop i:hover {
color: #f3f3f3;
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-up:before {
content: "\e686";
box-sizing: border-box;
}
.icon-under:before {
content: "\e685";
box-sizing: border-box;
}
js部分(选择跳转文末时,如果页面包含grade样式,则跳转至grade截止,grade区域在屏幕位置上下居中,如果页面没有包含grade样式的标签,则跳转到footer样式位置):
//返回顶部和返回头部
$("#backtotop").each(function() {
$(this).find(".gotop").click(function() {
$("html, body").animate({
"scroll-top": 0
},
"fast")
});
//如果页面中包含grade样式则跳转到grade,否则跳转到footer位置
$(".gobottom").click(function() {
if ($(".grade").length) {
$("html, body").animate({
scrollTop: $(".grade").offset().top - ($(window).height() - $(".grade").outerHeight()) / 2
}, 800);
} else {
$("html, body").animate({
scrollTop: $(".footer").offset().top
}, 800);
}
return false;
});
});
var d = false;
$(window).scroll(function() {
var j = $(window).scrollTop();
if (j > 500) {
$("#backtotop").data("expanded", true)
} else {
$("#backtotop").data("expanded", false)
}
if ($("#backtotop").data("expanded") != d) {
d = $("#backtotop").data("expanded");
if (d) {
$("#backtotop .gotop").slideDown()
} else {
$("#backtotop .gotop").slideUp()
}
}
});