返回顶部插件
作者:
秒速五厘米
代码
html
<style>
.back_top {
width: 30px;
height: 30px;
background: #1CAF9A;
text-align: center;
border-radius: 3px;
cursor: pointer;
opacity: 0.5;
}
.back_top i {
color: white;
line-height: 30px;
font-size: 12px;
}
</style>
<script src="/js/backTop.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function () {
//插件使用
$('.back_top').backTop({right: 30});
})
</script>
<div class="back_top hidden-xs hidden-md">
<i class="fa fa-angle-up" aria-hidden="true">i>
div>
backTop.js
(function ($) {
//这里放入插件代码
//起插件名称叫backTop
$.fn.backTop = function(options){
//设置默认值
var defaultValue = {
'bottom': 10, //距离底部为20
'right' : 10, //距离右侧为20
'speed' : 700 //返回顶部的时间
};
//用户如果传递则走用户的,否则走默认值
var resultOptions = $.extend(defaultValue,options);
//比如$('.backTop').backTop(); 那么当前对象$(this)就是$('.backTop')
var _this = $(this);
_this.css({
'position':'absolute',
'bottom': resultOptions.bottom,
'right': resultOptions.right,
'display':'none'
})
//滚动条滚动
$(document).scroll(function(){
var top = $(window).height() - _this.height() - resultOptions.bottom + $(this).scrollTop();
_this.css({top : top });
//判断什么时候出现
if($(this).scrollTop()>=10){
_this.fadeIn(500);
}else{
_this.fadeOut(500);
}
})
//点击返回顶部
_this.click(function(){
$('html,body').animate({scrollTop:0},resultOptions.speed);
})
}
})(jQuery);