<!DOCTYPE html>
<head>
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.a {
position: relative;
width: 600px;
height: 600px;
border: 1px solid red;
}
.b {
position: absolute;
width: 200px;
height: 200px;
background-color: blueviolet;
}
</style>
</head>
<body>
</div>
</div>
<!-- <div class="b"></div> -->
./jquery-1.12.4.js"></script>
./tuozhuai.js"></script>
<script>
/* 在局部方位内拖拽组件可以使用传参 */
/* 默认配置 是在document中移动div */
/* el是传子元素的标签或者类名 box是传父元素的标签或者类名 */
$('.b').tuozhuai({
el: '.b',
box: '.a'
});
</script>
</body>
</html>
tuozhuai.js
(function () {
$.fn.extend({
tuozhuai: function (obj) {
/* 默认配置 是在document中移动div */
let o = {
el:'div',
box:document
};
$.extend(o,obj)
$(o.el).mousedown(function (e) {
let event = e || event;
let l = event.clientX - $(this).offset().left;
let t = event.clientY - $(this).offset().top;
$(o.box).mousemove(function (e) {
/* 动态的获取移动div的时候的鼠标的位置 */
let e2 = e || event;
let left = e2.clientX - l;
let top = e2.clientY - t;
let maxw = $(o.box).width() - $(o.el).width();
let maxh = $(o.box).height() - $(o.el).height();
if (left < 0) left = 0;
if (top < 0) top = 0;
if (left > maxw) left = maxw;
if (top > maxh) top = maxh;
$(o.el).css({ left: left + 'px', top: top + 'px' })
})
$(o.box).mouseup(function () {
$(o.box).off('mousemove')
})
})
}
})
})()
网友评论