本文实例为大家分享了基于jQuery封装的拖拽事件,供大家参考,具体内容如下
HTML代码:
document *{ padding: 0; margin: 0; } .box{ height: 200px; width: 200px; background-color: red; position: absolute; user-select:none; } box
封装的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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



