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)