1.说明
只需要填入需要可拖动的元素的class值就实现了,支持多个元素。拖动时自动把元素放在顶层,防遮挡。只有电脑端可用手机端不行。本人自学的代码质量有所欠佳,欢迎大佬指出错误。
2.使用方法
2.1 这块代码块直接复制到js里就可以调用
//可移动的
function movealbe(classArr){
var MoveItem,ZI;
classArr.forEach(function(item){
theClassNum = document.getElementsByClassName(item);
for(i=0;i<theClassNum.length;i++){
var movealbeItem = document.getElementsByClassName(item)[i];
movealbeItem.onmousedown=function(e){
ZI = this.style.zIndex;
this.style.zIndex=99999;
var x=e.screenX,y=e.screenY;
var position = this.style.transform.slice(10,-1).split(',');
try{
var dx = position[0].slice(0,-2),dy=position[1].slice(0,-2);
}
catch(er){
dx=0,dy=0;
}
MoveItem = this;
document.onmousemove=function(e){
MoveItem.style.transform=`translate(${Number(dx)+e.screenX-x}px,${Number(dy)+e.screenY-y}px)`;
}
}
this.onmouseup=function(){
MoveItem.style.zIndex=ZI;
document.onmousemove='';
}
}
});
}
2.2 调用方法:把moveable()写在界面加载完成的事件后。参数必须是数组,里面是该元素的class值,同class值的元素会匹配全部。
window.onload=function(){
movealbe(['a','b']);
}
3.其他提示
3.1 拖动时如果有选中文字的效果。css可用user-select: none;消除。
3.2 拖动图片时有图片拽出来的效果,css给img添加-webkit-user-drag: none;消除。
3.3 更改鼠标指针为移动的效果,css可用cursor: move;解决。