Prepare a set of data
list: [
{
width: 100, height: 100, backgroundColor: 'blue' },
{
width: 100, height: 100, backgroundColor: '#e8693f' },
{
width: 150, height: 50, backgroundColor: '#409215' },
{
width: 50, height: 100, backgroundColor: '#928815' },
{
width: 120, height: 30, backgroundColor: '#6f1592' }
]
HTML
<div class="box">
<div
v-for="(item,i) in list"
:key="i"
class="item"
:style="getStyle(item,i)"
@mousedown="drag($event,i)"
/>
</div>
JS
drag(e, i) {
const dom = document.getElementsByClassName('item')[i]
const box = document.getElementsByClassName('box')[0]
// 计算鼠标位置和元素偏移量的差值。
const ol = e.clientX - dom.offsetLeft
const tl = e.clientY - dom.offsetTop
document.onmousemove = (t) => {
t.preventDefault()
// 拖拽事件
let left = t.clientX - ol
let top = t.clientY - tl
const offsetRight = box.offsetWidth - dom.offsetWidth
const offsetBottom = box.offsetHeight - dom.offsetHeight
if (left < 0) {
left = 0 }
if (left > offsetRight) {
left = offsetRight }
if (top < 0) {
top = 0 }
if (top > offsetBottom) {
top = offsetBottom }
dom.style.left = left + 'px'
dom.style.top = top + 'px'
}
document.onmouseup = () => {
document.onmousemove = null
document.onmouseup = null
}
},
// 动态设置样式
getStyle(item, i) {
let left = 0
for (let j = 0; j < i; j++) {
left += this.list[j].width
}
const str = `width: ${
item.width}px;
height:${
item.height}px;
background-color:${
item.backgroundColor};
position: absolute;
left:${
left}px`
return str
},
CSS
.box{
width: 1000px;
height: 500px;
border: 1px solid #000;
margin: auto;
position: relative;
}
renderings