HTML部分给div设置绝对定位,div即被拖拽的元素
1、使用原生js实现实现拖拽效果
//div即拖拽的元素
const [div, w, h] = [
document.querySelector('div'),
document.documentElement.clientWidth,
document.documentElement.clientHeight,
]
div.addEventListener('mousedown', (e1) => {
document.onmousemove = (e2) => {
div.style.top =
(e2.clientY - e1.offsetY < 0 ? 0 : e2.clientY - e1.offsetY + 'px') &&
(e2.clientY - e1.offsetY > h - div.offsetHeight ? h - div.offsetHeight + 'px' : e2.clientY - e1.offsetY + 'px')
div.style.left =
(e2.clientX - e1.offsetX < 0 ? 0 : e2.clientX - e1.offsetX + 'px') &&
(e2.clientX - e1.offsetX > w - div.offsetWidth ? w - div.offsetWidth + 'px' : e2.clientX - e1.offsetX + 'px')
}
div.onmouseup = () => document.onmousemove = null
})
2、使用jQuery实现实现拖拽效果
(function ($) {
$.fn.drag = function () {
const _this = $(this);
let offsetX, offsetY;
_this.mousedown(function (e) {
offsetX = e.pageX - $(this).offset().left;
offsetY = e.pageY - $(this).offset().top;
$(document).mousemove(onmousemove);
$(document).mouseup(function () {
$(this).off();
});
});
function onmousemove(e) {
let X = e.pageX - offsetX;
let Y = e.pageY - offsetY;
//判断是否出界
let left = (X < 0 ? 0 : X) && (X > $(window).width() - _this.outerWidth() ? $(window).width() - _this.outerWidth() : X);
let top = (Y < 0 ? 0 : Y) && (Y > $(window).height() - _this.outerHeight() ? $(window).height() - _this.outerHeight() : Y);
_this.css({
left: left + "px",
top: top + "px",
});
}
};
})(jQuery);
$(function () {
$("div").drag();
});
3、在移动端基于 touch.js & zepto.js 实现拖拽效果(思路与jQuery一致)
$(function () {
$(".box").on("dragstart", function fn(e) {
const _this = $(this);
let ew = $(this).width(); //元素宽
let eh = $(this).height(); //元素高
let mx = e.detail.position.x; //触摸点x坐标
let my = e.detail.position.y; //触摸点y坐标
let offsetX = mx - $(this).offset().left; //元素离窗口左侧距离
let offsetY = my - $(this).offset().top; //元素离窗口上侧距离
$(document).on("drag", ondrag);
$(document).on("dragend", function () {
$(this).off();
});
function ondrag(e) {
let X = e.detail.position.x - offsetX;
let Y = e.detail.position.y - offsetY;
//计算元素是否出界
let left = (X < 0 ? 0 : X) && (X > $(window).width() - ew ? $(window).width() - ew : X);
let top = (Y < 0 ? 0 : Y) && (Y > $(window).height() - eh ? $(window).height() - eh : Y);
_this.css({
left: left + "px",
top: top + "px",
});
}
});
});