当前位置: 代码迷 >> 综合 >> 【加强版】js原生实现拖拽效果,这次没有用document的mousedown、mousemove、mouseup事件我们来点实际的(但是有个弊端:拖拽过程中鼠标会变成一个禁用符号,不太友好)
  详细解决方案

【加强版】js原生实现拖拽效果,这次没有用document的mousedown、mousemove、mouseup事件我们来点实际的(但是有个弊端:拖拽过程中鼠标会变成一个禁用符号,不太友好)

热度:42   发布时间:2023-11-27 19:20:16.0

 

<div class='dragged'></div>
    //初始化需要拖拽的列initDrags() {var arr = document.querySelectorAll(".dragged");for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];this.drag(a);}},// js原生实现拖拽效果drag(sel) {var dragged = typeof sel === "string" ? document.querySelector(sel) : sel;dragged.draggable = true; //开启拖拽属性(不加这句话拖不动)// 开始拖拽dragged.ondragstart = function(event) {var event = event || window.event; //兼容IE浏览器// 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离this.diffX = event.clientX - this.offsetLeft;this.diffY = event.clientY - this.offsetTop;};//拖拽中…dragged.ondrag = function(event) {this.setAttribute("dragging", "true"); //拖拽过程变成虚线的样子var event = event || window.event;var x = event.clientX - this.diffX;var y = event.clientY - this.diffY;if (x < 0) {x = 0;} else if (x > innerWidth - this.offsetWidth) {x = innerWidth - this.offsetWidth;}if (y < 0) {y = 0;} else if (y > innerHeight - this.offsetHeight) {y = innerHeight - this.offsetHeight;}this.style.left = x + "px"; //左右拖拽this.style.top = y + "px"; //上下拖拽};//拖拽结束dragged.ondragend = function(event) {this.removeAttribute("dragging"); //取消虚线样式};},
.dragged { transition: none !important;/*禁止选中文本*/-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;cursor: grab !important;&:active {z-index: 1;cursor: grabbing !important;opacity: .618;}&[dragging] {cursor: grabbing !important;background: white !important;border: 1px dashed gray !important;color: gray !important;opacity: 0.9 !important;transform: translate(-3px, -3px);box-shadow: 5px 10px 0 rgba(0, 0, 0, 0.05);}&[animate] {transition: 0.618s ease;}
}

  相关解决方案