最近需要写一个回到顶部的小按钮让用户来点击回到顶部,写了一个很简单的小插件。
jquery编写插件一般就是通过$.extend()来扩展jquery,还有就是通过$.fn添加新的jquery方法、还有就是通过$.widget()应用jquery UI的部件工厂方式创建。
这里我就用得到$.fn来向jquery添加新的方法。下面就是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>回到顶部</title>
<style type="text/css">
* {
margin: 0px ;
padding: 0px ;
}
.box {
height: 300vh;
width: 100vw;
background: rgba(0, 0, 0, 0.5)
}
.toTop {
color: #000;
background: #fff;
position: fixed;
bottom: 5%;
right: 5%;
width: 80px;
height: 40px;
line-height: 40px;
text-align: center;
cursor: pointer;
display: none;
}
</style>
</head>
<body>
<div class="box">
这是顶部
</div>
<div class="toTop">点击向上</div>
<script src="http://www.jq22.com/jquery/jquery-2.1.1.js"></script>
<script type="text/javascript">
$(function () {
$.fn.toTop = function (param) {
var checkTop = function () { //检查页面距离顶部位置的函数
if ($(document).scrollTop() > 50) {
$('.toTop').fadeIn(param.showSpeed)
} else if ($(document).scrollTop() <= 50) {
$('.toTop').fadeOut(param.showSpeed)
}
};
checkTop();
$(document).scroll(function () {
checkTop();
});
$(document).on('click', param.topClass, function () {
$('body,html').animate({
scrollTop: 0
}, param.goTopSpeed);
});
};
$('.toTop').toTop({
showSpeed: 500,//向上按钮出现的速度
goTopSpeed: 500,//到顶部的时间
topClass:'.toTop'//按钮的class
})
});
</script>
</body>
</html>
这样子一个回到顶部简单的小插件就写好了。可以把js部分拿到单独的js文件里面,用到就引入调用函数toTop。