今天要做的拖拽如下图
将左侧元素拖拽到右边框,右边是个超过滚动的盒子。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jQuery.js"></script>
<style>
.drafting_box{
display: flex;
border: 1px solid #000;
border-radius: 6px;
height: 600px;
}
.drafting_box .nav_list,
.drafting_box .show_box{
height: 100%;
overflow: auto;
}
.drafting_box .nav_list{
width: 100px;
border-right: 1px solid #000;
padding: 15px;
}
.drafting_box .show_box{
position: relative;
flex: 1;
}
.item{
display: inline-block;
padding: 5px 8px;
background-color: aqua;
border-radius: 4px;
cursor: pointer;
margin: 6px;
}
.tree_wrap{
width: 100%;
height: 100%;
overflow: auto;
}
.tree{
width: 1500px;
height: 800px;
position: relative;
}
.add{
position: absolute;
left: 10px;
top: 10px;
width: 40px;
height: 30px;
text-align: center;
line-height: 30px;
background-color: aqua;
border-radius: 4px;
cursor: pointer;
}
span{
position: absolute;
padding: 5px 8px;
border-radius: 4px;
background-color: green;
}
</style>
</head>
<body>
<div class="drafting_box">
<div class="nav_list ruleList">
<div class="item" onselectstart="return false">规则1</div>
<div class="item" onselectstart="return false">规则2</div>
<div class="item" onselectstart="return false">规则3</div>
<div class="item_2" onselectstart="return false"></div>
</div>
<div class="show_box">
<div class="add" onclick="showScroll()">add</div>
<div class="tree_wrap">
<div class="tree">
</div>
</div>
</div>
</div>
<script>
function showScroll(){
console.log( $('.tree_wrap').position());
console.log( $('.tree_wrap').scrollTop());
console.log( $('.tree_wrap').scrollLeft());
}
function createCell(opt){
console.log(opt);
var html = $('<span class="cell">'+opt.text+'</span>');
$('.tree').append(html);
$(html).css({
left:opt.x - opt.deflectX,
top:opt.y - opt.deflectY
});
}
(function drag(){
var position, tempEle,deflectX,deflectY;
$('.ruleList .item').on('mousedown',function(e){
console.log(e.target);
deflectX = e.offsetX;
deflectY = e.offsetY;
$('body').attr('onselectstart','return false');
$('.show_box').css('pointerEvents','none');
$('.tree').css('pointerEvents','initial');
position = $(this).position();
tempEle = $(this).clone();
tempEle.addClass('tempRule');
tempEle.css({
position:'absolute',
left:position.left,
top:position.top
});
$('.ruleList').append(tempEle);
var initX = e.clientX,
initY = e.clientY;
$(document).on('mousemove',function(e){
var curX = e.clientX,
curY = e.clientY;
tempEle.css({
left:curX - initX + position.left,
top:curY - initY + position.top
});
})
});
$(document).on('mouseup',function(e){
console.log(e.offsetY);
$('body').attr('onselectstart','return true');
$('.show_box').css('pointerEvents','initial');
//根据被拖进来元素生成元素
var tempRule = $('.tempRule');
if($(e.target).hasClass('tree') && tempRule.length>0){
createCell({
text:tempRule.text(),
x:e.offsetX,
y:e.offsetY,
deflectX:deflectX || 0,
deflectY:deflectY || 0,
});
}
tempRule.remove();
})
})();
</script>
</body>
</html>