实现步骤
源码
#panelsBox>div>.panel{ position: relative; }
/** * 拖拽面板 到某个面板的位置,交换两个面板位置 * 若没有到任意一个面板位置,则被拖拽面板回原位置 */ $(function(){ //1.监听 mousedown 事件 $("#panelsBox").on('mousedown','.panel',function(e){ var target_index = $(this).parent().attr("data-index");//被拖动面板元素位置 var targetX = e.pageX - parseInt($(this).css("left")); var targetY = e.pageY - parseInt($(this).css("top")); $(this).fadeTo(20, 0.5);//点击后开始拖动并透明 $(this).css("z-index",100);//设置优先展示 //2.监听当前被拖拽的面板的移动事件:鼠标移动到何处,相应面板的css控制显示到何处 $(this).mousemove(function(e){ var x = e.pageX - targetX;//移动时根据鼠标位置计算面板元素左上角的相对位置 var y = e.pageY - targetY; $(this).css({top:y,left:x});//设置面板元素新位置 }).mouseup(function(e){ //3.监听鼠标松开事件:交换面板元素,并将父级data-index换为原来的值 $(this).fadeTo("fast", 1);//停止移动并恢复成不透明 $(this).css("z-index",0);//展示优先级降低 //鼠标松开对应的面板元素的父div对应data-index var exchangeElem = $(document.elementFromPoint(e.pageX,e.pageY)).parents(".panel"); if(exchangeElem.length > 0){ var exchange_index = $(exchangeElem[0]).parent("div").attr("data-index"); var device_id_target = $(exchangeElem[0]).parent("div").attr("data-device-id"); device_id_target = device_id_target == undefined?"":device_id_target; if(target_index != exchange_index){ //交换面板元素 $("#panelsBox").children("div[data-index=" + target_index + "]").empty().append(exchangeElem[0]); $("#panelsBox").children("div[data-index=" + exchange_index + "]").empty().append(this); $("#panelsBox").children("div[data-index=" + exchange_index + "]").children(".panel").css({'top':"0px",'left':"0px",'z-index':0}); //交换data-index $("#deviceList").children("div[data-index=" + target_index + "]") attr("data-index",exchange_index); $(document.elementFromPoint(e.pageX,e.pageY)).parents(".panel").parent() .attr("data-index",target_index); }else{ //返回原位置 $(this).css({'top':"0px",'left':"0px",'z-index':0}); } }else{ //返回原位置 $(this).css({'top':"0px",'left':"0px",'z-index':0}); } }); }); });
www.dengb.comtruehttp://www.dengb.com/jQuery/1413877.htmlTechArticlejQuery 实现DOM元素拖拽交换位置, 实现步骤 源码 html 代码: !DO
—-想了解更多的jQuery特效教程关注
本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ssfiction.com/jqyjc/124296.html