<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.flu{float: left;margin-left: 20px;}
.node{width: 120px;height: 50px;border: 1px solid red;;margin-right: 20px;float: left;}
</style>
</head>
<body>
<div class="flu">
<div class="node" id="node1"></div>
<div class='node' id="node2"></div>
</div>
<script type="text/javascript">
var node=document.getElementsByClassName('node');
//获取每个div的偏移量
var arr=[];
for(var i=0;i<node.length;i++){
arr.push([node[i].offsetLeft,node[i].offsetTop]);
}
//把拖拽元素改为定位布局
for(var i=0;i<node.length;i++){
node[i].style.left=arr[i][0]+'px';
node[i].style.top=arr[i][1]+'px';
node[i].style.position='absolute';
node[i].style.margin=0;
}
//给每个div绑定拖拽功能
for(var i=0;i<node.length;i++){
drag(node[i]);
}
function drag(obj){
obj.onmousedown=function(e){
var e = event || window.event;
//获取偏移量
disX = e.clientX - obj.offsetLeft;
disY = e.clientY - obj.offsetTop;
//鼠标移动事件
document.onmouseover=function(ev){
var ev = event || window.event;
//确定拖拽元素最后的新位置
var l = ev.clientX - disX;
t = ev.clientY - disY;
obj.style.left = l + 'px';
obj.style.top = t + 'px';
}
//鼠标松开事件
document.onmouseup=function(){
document.onmouseover=null;
}
}
}
</script>
</body>
</html>
添加回答
举报
0/150
提交
取消