js实现拖动其中一个div多个div同时移动
来源:原创
时间:2018-07-15
作者:脚本小站
分类:JS/JQuery
<div id="room"> <button class="desk" style="top:20px;left:100px;" ></button> <button class="desk" style="top:120px;left:130px;" ></button> </div>
拖动其中一个div实现多个div同时移动:
$(document).on('mousedown','.desk',function (e) { console.log('multi'); var roomOffset = $('#room').offset(); var deskObj = $('.desk'); /* 这里的 e.pageX 为 mousedown 的位置, roomOffset.left 为最外层的div到body的距离 */ var isMove = true; var div_x = []; //鼠标点下时每一个 .desk 各自到 body 的左边距离,这个值在鼠标移动的时候是不变的 var div_y = []; for(var i = 0;i < MULTI_SELECTION_INDEX.length;i++){ var offset = deskObj.eq(MULTI_SELECTION_INDEX[i]).offset();// .desk 左上角到body的距离 div_x[i] = e.pageX - offset.left + roomOffset.left; div_y[i] = e.pageY - offset.top + roomOffset.top; } $(document).mousemove(function (e) { if (isMove) { for(var i = 0;i < MULTI_SELECTION_INDEX.length;i++){ deskObj.eq(MULTI_SELECTION_INDEX[i]).css({"left":e.pageX - div_x[i], "top":e.pageY - div_y[i]}); } } }).mouseup(function () { isMove = false; $(document).unbind('mousemove'); $(document).unbind('mouseup'); }); });
移动单个div:
$(document).on('mousedown','.desk',function (e) { console.log('signle'); $(this).css({background:'#44c5ff'}).siblings().css({background:'white'}); CURRENT_DISK = $(this).index(); var roomOffset = $('#room').offset(); var moveObj = $(this); var offset = moveObj.offset(); var div_x = e.pageX - offset.left + roomOffset.left; var div_y = e.pageY - offset.top + roomOffset.top; var isMove = true; $(document).mousemove(function (e) { if (isMove) { moveObj.css({"left":e.pageX - div_x, "top":e.pageY - div_y}); } }).mouseup(function () { isMove = false; $(document).unbind('mousemove'); $(document).unbind('mouseup'); }); });