界面拖拽交互
实现一个可拖拽交互的界面
如示例图,左右两侧各有一个容器,里面的选项可以通过拖拽来左右移动
被选择拖拽的容器在拖拽过程后,在原容器中消失,跟随鼠标移动
注意拖拽释放后,要添加到准确的位置
本来看到这个我的想法是把大盒子套小盒子,后面才想起要在页面拖拽小盒子的不能套娃,最后选择了绝对定位,然后鼠标点击拖动,松开就定下,这里最难受的一点就是定义小盒子被吸进大盒子的位置,我真的要被这些距离的属性搞傻了。。。勉勉强强做了
现在想优化的就是把重复的代码封装起来,以及拖动盒子的时候流畅一点,被吸进盒子的时候也不要有卡顿的感觉(估计是靠定时器?)
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
body {
position: relative;
}
#left {
display: inline-block;
height: 500px;
width: 200px;
border: 1px solid #000000;
margin-right: 150px;
}
#right {
display: inline-block;
height: 500px;
width: 200px;
border: 1px solid #000000;
}
.box1 {
position: absolute;
top: 50px;
display: flex;
width: 200px;
height: 50px;
background-color: red;
border: 1px solid #000000;
}
.box2 {
position: absolute;
top: 0px;
display: flex;
width: 200px;
height: 50px;
background-color: red;
border: 1px solid #000000;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div id="left"></div>
<div id="right"></div>
<script>
window.onload = function() {
document.addEventListener('mousedown', function(e) {
// console.log(e.clientX); //207 364
// console.log(e.clientY);
})
var box1 = document.querySelector('.box1');
var box2 = document.querySelector('.box2');
box1.addEventListener('mousedown', function(e) {
var x = e.pageX - box1.offsetLeft;
var y = e.pageY - box1.offsetTop;
document.addEventListener('mousemove', move);
function move(e) {
if ((e.pageX - x) > 250) {
//console.log('success');
box1.style.left = 356 + 'px';
} else if ((e.pageX - x) <=100) {
box1.style.left = 0 + 'px';
} else {
box1.style.left = e.pageX - x + 'px';
box1.style.top = e.pageY - y + 'px';
}
}
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move);
})
})
box2.addEventListener('mousedown', function(e) {
var x = e.pageX - box2.offsetLeft;
var y = e.pageY - box2.offsetTop;
/* console.log(x);
console.log(y); */
document.addEventListener('mousemove', move);
function move(e) {
if ((e.pageX - x) > 250) {
//console.log('success');
box2.style.left = 356 + 'px';
} else {
box2.style.left = e.pageX - x + 'px';
box2.style.top = e.pageY - y + 'px';
}
}
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move);
})
})
}
</script>
</body>
</html>