今天给大家分享的是关于基于jQuery封装的拖拽事件,下文有详细的代码及注释,对大家学习和理解封装以及拖拽事件都有一定的帮助,有需要的朋友可以参考。
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery-3.4.1.min.js"></script>
<script src="Drag.js"></script>
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
.box{
height: 200px;
width: 200px;
background-color: red;
position: absolute;
/* 让文字无法被选中 */
user-select:none;
}
</style>
</head>
<body>
<div class="box"></div>box</div>
<script>
$('.box').Drag();//直接调用Drag()方法就可以了
</script>
</body>
</html>
封装的jQuery拖拽事件:
;(function($) {
$.fn.extend({
Drag(){
//把this存起来,始终指向操作的元素
_this = this;
this.on('mousedown',function (e) {
//盒子距离document的距离
var positionDiv = $(this).offset();
//鼠标点击box距离box左边的距离
var distenceX = e.pageX - positionDiv.left;
//鼠标点击box距离box上边的距离
var distenceY = e.pageY - positionDiv.top;
$(document).mousemove(function(e) {
//盒子的x轴
var x = e.pageX - distenceX;
//盒子的y轴
var y = e.pageY - distenceY;
//如果盒子的x轴小于了0就让他等于0(盒子的左边界值)
if (x < 0) {
x = 0;
}
//盒子右边界值
if(x > $(document).width() - _this.outerWidth()){
x = $(document).width() - _this.outerWidth();
}
//盒子的上边界值
if (y < 0) {
y = 0;
}
//盒子的下边界值
if(y > $(document).height() - _this.outerHeight()){
y = $(document).height() - _this.outerHeight();
}
//给盒子的上下边距赋值
$(_this).css({
'left': x,
'top': y
});
});
//在页面中当鼠标抬起的时候,就关闭盒子移动事件
$(document).mouseup(function() {
$(document).off('mousemove');
});
})
//把this返回回去继续使用jqurey的链式调用
return this
}
})
})(jQuery)
关于jQuery拖拽事件的封装就介绍到这,希望大家阅读完这篇文章能有所收获,想要了解更多jQuery拖拽事件的内容,大家可以关注群英网络其它相关文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理