元素拖拽效果

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",
      });
    }
  });
});

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值