每天一个jquery插件-做缩放插件1
做缩放插件1
有人说jqueryui很老了,用来开发项目不值得,所以我打算自己研究研究,目标是弄懂工作原理之后就能方便自己拓展啦
效果如下
代码部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>就是jqueryui里面的Resizable</title>
<script src="js/jquery-3.4.1.min.js"></script>
<style>
*{
margin: 0px;
padding: 0px;
user-select: none;
}
#div{
border: 1px solid lightgray;
height: 400px;
width: 600px;
margin: 20px;
}
.rel{
position: relative;
}
.resbar{
border:1px solid lightgray;
width: 15px;
height: 15px;
position: absolute;
bottom: -10px;
right: -10px;
cursor: se-resize;
}
.stopclick{
pointer-events: none;
}
</style>
</head>
<body>
<div id="div"></div>
</body>
</html>
<script>
$(function(){
$("#div").res();
})
$.prototype.res = function(){
//前期准备
var $that = $(this);
var that = this;
$that.addClass("rel");
var $bar = $("<div class='resbar'></div>");
$bar.appendTo($that);
//声明参数
//点击时坐标
var pos1 = getbarpos();
//拖拽时鼠标的位置
var pos2 = {
l:0,t:0};
//动作
var flag = false;
$that.mousedown(function(){
flag = true;
}).mouseup(function(){
flag = false;
})
$(document).mousemove(function(e){
if(flag){
$that.addClass('stopclick')
pos2 = geteventpos(e);
//两个坐标点都知道了,然后就是变化dom宽度了
thatchange();
}else{
$that.removeClass('stopclick')
pos1 = getbarpos();
}
}).mouseup(function(){
flag=false;
})
function thatchange(){
var w = $that.width()+(pos2.l-pos1.l)/20;
var h = $that.height()+(pos2.t-pos1.t)/20;
$that.width(w)
$that.height(h)
}
function getbarpos(){
return {
l:$bar.offset().left,t:$bar.offset().top};
}
function geteventpos(e){
return {
l:e.clientX,t:e.clientY};
}
}
</script>
思路解释
- 简单的认为这个功能就是给目标容器加上一个看不见的拖拽框框,然后在这上面触发动作
- 记录起始的坐标点,然后拖拽的缩放的时候把俩参数之间的差值反应到容器的高宽上
- 不过我虽然做出来效果了,但是这个拖拽变化有点摸不着头脑,我以为这个参数的变化时一比一的,但是实际上拖拽起来我的容器不知道膨胀到哪去了,所以这里面event给的坐标点的单位不是px?还是我写的有问题,然后我就给差值除了一个比例的值,勉强能测试了。
- 不过还是比较蹩脚的实现,等明天有空再继续弄弄
- 没完,碎觉~