<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
padding: 0;
margin: 0;
}
#console{
width: 500px;
height: 500px;
background: #eee;
margin: 10px auto;
border: 5px solid #000;
}
#menubar{
width: 100%;
height: 30px;
background: #333;
line-height: 30px;
vertical-align: middle;
}
#addItem{
width: 80px;
height: 20px;
color: #fff;
background: #555;
border: 0;
line-height: 20px;
margin-left: 5px;
border-radius: 5px;
}
#nodesContainer{
width: 100%;
height: 270px;
background: #eee;
}
.newNode{
position: absolute;
width: 50px;
height: 50px;
background: blue;
border-radius: 50%;
}
</style>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="console">
<div id="menubar">
<input type="button" id="addItem" value="点击添加节点" />
</div>
<div id="nodesContainer"></div>
</div>
</body>
<script>
$(function(){
$('#addItem').click(function(){
var newNode = document.createElement('div');//直接创建时dom对象,需要转换为jq对象使用
var r =Math.round( Math.random()*255);
var g =Math.round( Math.random()*255);
var b =Math.round( Math.random()*255);
$(newNode).addClass('newNode').css("background","rgba("+r+","+g+","+b+",0.5)");
$('#nodesContainer').append(newNode);
var nd = $('#nodesContainer').children();
doDrag(nd)
});
});
function doDrag(nd){
var posX,posY;
nd.mousedown(function(event){
posX = event.clientX - $(this).offset().left;
posY = event.clientY - $(this).offset().top;
var that = $(this);
var sb = that.siblings();
$(document).on('mousemove',function(e){
that.css({'left':(e.clientX - posX),'top':e.clientY - posY});
for(var i = 0 ; i < sb.length ; i ++){
if(Math.abs(that.offset().left-sb[i].offsetLeft)<50&&Math.abs(that.offset().top-sb[i].offsetTop)<50){
that.remove();
$(sb[i]).remove();
}
}
})
})
nd.mouseup(function(){
$(document).off('mousemove')
});
}
</script>
</html>