【墙裂推荐】【原生基础版】js原生实现拖拽效果,注意不要忘了div的cursor用grab和grabbing 还是古法炮制、传统工艺的原生代码兼容性最好,推荐
生活随笔
收集整理的這篇文章主要介紹了
【墙裂推荐】【原生基础版】js原生实现拖拽效果,注意不要忘了div的cursor用grab和grabbing 还是古法炮制、传统工艺的原生代码兼容性最好,推荐
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
以下方式的劣勢就是在放棄拖拽那一刻會觸發click事件,通常如果被拖拽元素還有其他點擊事件,會重復觸發,往往并非業務需求。優勢就是…額…貌似這段代碼沒什么屌優勢!?
<div class='dragged' draggable='true'></div>
HTML5為所有HTML元素規定了一個draggable屬性,表示元素是否可以拖動,圖像和鏈接的draggable屬性自動被設置成了true,而其他元素這個屬性的默認值都是false。
[注意] Angular下必須設置draggable='true'才能生效,只設置draggable不起作用
// 初始化需要拖拽的列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;// 點擊某物體時,用drag對象即可,move和up是全局區域,// 也就是整個文檔通用,應該使用document對象而不是drag對象(否則,采用drag對象時物體只能往右方或下方移動)dragged.onmousedown = function(event) {var event = event || window.event; //兼容IE瀏覽器// 鼠標點擊物體那一刻相對于物體左側邊框的距離=點擊時的位置相對于瀏覽器最左邊的距離-物體左邊框相對于瀏覽器最左邊的距離var diffX = event.clientX - dragged.offsetLeft;var diffY = event.clientY - dragged.offsetTop;if (typeof dragged.setCapture !== "undefined") {dragged.setCapture();//防止拖拽的時候鼠標離開了div范圍就沒辦法移動了}
//這個地方一般不建議直接用document,最好用document.querySelector("容器"),以免和其他子元素的onmousemove沖突,但是務必確保移動范圍是在容器范圍內,否則出界就無法移動了document.onmousemove = function(event) {dragged.setAttribute("dragging", "true"); //拖拽過程變成虛線的樣子var event = event || window.event;var x = event.clientX - diffX;var y = event.clientY - diffY;if (x < 0) {x = 0;} else if (x > window.innerWidth - dragged.offsetWidth) {x = window.innerWidth - dragged.offsetWidth;}if (y < 0) {y = 0;} else if (y > window.innerHeight - dragged.offsetHeight) {y = window.innerHeight - dragged.offsetHeight;}dragged.style.left = x + "px";//左右拖拽dragged.style.top = y + "px";//上下拖拽};
//這個地方一般不建議直接用document,最好用document.querySelector("容器"),以免和其他子元素的onmouseup沖突,但是務必確保移動范圍是在容器范圍內,否則出界就無法松開了document.onmouseout = document.onmouseup = function(event) {dragged.removeAttribute("dragging"); //取消虛線樣式this.onmousemove = null;this.onmouseup = null;//修復低版本ie bugif (typeof dragged.releaseCapture != "undefined") {dragged.releaseCapture();}};};},
.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;&:active {z-index: 1;cursor: grabbing;opacity: .618;}&[dragging] {cursor: grabbing;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;}
}
總結
以上是生活随笔為你收集整理的【墙裂推荐】【原生基础版】js原生实现拖拽效果,注意不要忘了div的cursor用grab和grabbing 还是古法炮制、传统工艺的原生代码兼容性最好,推荐的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 喂~讲真~我很讨厌chrome谷歌浏览器
- 下一篇: 【加强版】js原生实现拖拽效果,这次没有