每天一个jquery插件-做置顶插件2
做置顶插件2
额,前面遇到的问题没找到自带的解决办法,所以我自己想着就换其他方式实现效果了
效果如下
代码部分
.rel{
position: relative;
}
.btn{
user-select: none;
position: absolute;
width: 50px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
background-color: white;
border:1px solid lightgray;
font-size:24px;
}
.btnfixed{
position:fixed;
right: 10px;
bottom: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>做置顶特效</title>
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/zzdtx.js"></script>
<link href="css/zzdtx.css" rel="stylesheet" type="text/css" />
<style>
*{
margin: 0;
padding: 0;
}
#test1{
background-color: white;
width: 100%;
height: 1500px;
}
#test2{
background-color: lightgray;
width: 300px;
height: 500px;
overflow: auto;
}
#test3{
background-color: gray;
width: 200px;
height: 700px;
}
</style>
</head>
<body>
<div id="test1">
<div id="test2">
<div id="test3"></div>
</div>
</div>
</body>
</html>
<script>
$(function(){
var temp1 = zzdtx("body");
var temp2 = zzdtx("#test2");
temp1.load();
temp2.load();
})
</script>
var zzdtx = function(id) {
var $id = $(id);
$id.parent().addClass('rel')
var $btn = $("<div class='btn'>↑</div>");
$btn.appendTo($id.parent())
if(id!="body"){
$btn.css({
"left":$id[0].offsetLeft+$id.width()-60+"px",
"top":$id[0].offsetTop+$id.height()-60+"px"
})
}else{
$btn.addClass("btnfixed")
}
$btn.hide();
return {
id:id,
$btn:$btn,
$id: $id,
top:top,
load: function(top) {
var that = this;
that.top = top==undefined?100:top;
that.$btn.click(function(){
//点击置顶
if(that.id!='body'){
that.$id.stop().animate({
scrollTop:'0px'
})
}else{
$('html').stop().animate({
scrollTop:'0px'
})
}
})
//状态监控
if(that.id!='body'){
that.$id.scroll(function(){
var temp = $(this).scrollTop();
if(temp>that.top){
that.$btn.show();
}else{
that.$btn.hide();
}
})
}else{
$(document).scroll(function(){
var temp = $(document).scrollTop();
if(temp>that.top){
that.$btn.show();
}else{
that.$btn.hide();
}
})
}
}
}
}
解释想法
- 前面想要弄个自带的办法来把按钮固定在可视区域,但是没找着,所以打算自己找办法实现
- 然后这里面一开始想要一个办法做完,但是因为html与body的关系这个置顶得分开条件写着
- 最后按照js的想法是这样了,假如是给浏览器加置顶按钮,那就按照通常的方法实现fixed定位按钮位置就行了,假如是一个div容器,那就给做一个直接计算出这个目标容器在它父容器的相对位置,然后计算出对应的右下角的坐标点,把按钮定位浮动在这里就完事了,不过这里可能还有地方没写对,我只考虑了一次性写完的,假如目标容器后面还会四处飞来飞去那就会有问题了,当然要解决也有更多方式,就是我直接把这个目标容器里面所有的东西再额外用一层div包起来,滚动什么的都交给它,然后这样子置顶按钮的固定就可以相对目标容器用absolute定位了,额不过这个没做
- 完事,还早,去研究其他东西切了