添加置顶和到底按钮
蔡源茂 | 创建:2018-03-17 | 最后更新:2018-03-17 | 753次阅读
网上搜了下,发现实现的方法很多,我这里说说我的实现思路:(本博客已采用,github链接:九神小屋)
1. 在html页面中,增加一个按钮标签
<div class="jump_toolbar">
<div class="jump_top btn-move-page" data-type="top">
<div class="jump_top_in"></div>
<a href="#">回到顶部</a>
</div>
<div class="jump_bottom btn-move-page" data-type="bottom">
<div class="jump_bottom_in"></div>
<a href="#" >到达底部</a>
</div>
</div>
2. 通过css 控制,html标签显示到屏幕右下角排布,并通过transform和boder属性,画出置顶和到底按钮图样。
.jump_top,
.jump_bottom{
position:fixed;
right:40px;
bottom:140px;
height:50px;
width: 50px;
text-align:center;
padding-top:20px;
background-color: #0ebaa6;
border-radius: 20%;
overflow: hidden;
}
.jump_top_in,
.jump_bottom_in{
display:inline-block;
height:20px;
width: 20px;
border: 3px solid black;
border-color: #fff transparent transparent #fff;
transform:rotate(45deg);
-ms-transform:rotate(45deg); /* Internet Explorer */
-moz-transform:rotate(45deg); /* Firefox */
-webkit-transform:rotate(45deg); /* Safari 和 Chrome */
-o-transform:rotate(45deg); /* Opera */
}
.jump_top a,
.jump_bottom a {
display:none;
color:#fff;
height:40px;
width: 40px;
padding-top:5px;
text-decoration:none;
text-align:center;
font-weight:bold;
}
.jump_top:hover,
.jump_bottom:hover{
padding-top:0px;
}
.jump_top:hover .jump_top_in,
.jump_bottom:hover .jump_bottom_in{
display:none;
}
.jump_top:hover a,
.jump_bottom:hover a{
display:inline-block;
}
.jump_bottom{
bottom:80px;
padding-top:10px;
}
.jump_bottom_in{
border-color: transparent #fff #fff transparent;
}
.jump_bottom a {
padding-top:5px;
}
3. 通过js 实现点击置顶按钮时的窗口滑动效果。
监听div(类btn-move-page)的click事件,实现页面滑动。
我这里将click事件,添加进backbone监控中 不了解backbone?请点击Backbone官网
此处抄袭RubyChina代码,源码链接
coffescrip 代码:
#click事件,添加进backbone监控中
events:
"click .btn-move-page": "scrollPage"
scrollPage: (e) ->
target = $(e.currentTarget)
moveType = target.data('type')
opts =
scrollTop: 0
if moveType == 'bottom'
opts.scrollTop = $('body').height()
$("body, html").animate(opts, 300)
return false
4. 页面初始化时,设置 置顶和到底 按钮的显示状态
coffescrip 代码:
window_height=$(window).height() #获取当前窗口高度
body_height=$('body').height() #获取body标签高度
height = body_height - window_height
if $(window).scrollTop()==0
$('.jump_top').addClass("hide")
if $(window).scrollTop()==height
$('.jump_bottom').addClass("hide")
$(window).scroll ->
scrollTop_value=$(window).scrollTop()
if scrollTop_value>0
$('.jump_top').removeClass("hide")
else
$('.jump_top').addClass("hide")
if scrollTop_value<height
$('.jump_bottom').removeClass("hide")
else
$('.jump_bottom').addClass("hide")