2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
This week I took on a small outsourcing project, which required me to use Vue to achieve the drag effect shown in the following figure
@mousedown
Listen for mouse clicks and turn on after clickingmousemove + mouseup
Listener, and according toclientY + offsetTop
Calculate the new top height of the element and assign a value to achieve element following. The specific source code is as follows
<div title="demo" class="icon" @mousedown="demo">
<img src="../assets/logo.png" alt="">
<div class="icon_title" :style="{display: state.isShow ? 'block' : 'none'}">
拖拽下拉新增书签 <br /> 拖回顶部删除书签
</div>
</div>
demo(e) {
//去除默认样式 - 避免拖动元素出现禁止图标
e.preventDefault && e.preventDefault();
//获取目标元素
let odiv = e.target;
//算出鼠标相对元素的位置
let disY = e.clientY - odiv.offsetTop;
let item = {
top: 0,
id: 1,
url: '/src/assets/logo.png'
}
//监听鼠标移动事件
document.onmousemove = (e) => {
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let top = e.clientY - disY;
//重新赋值
item.top = top;
};
//监听鼠标松开
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
//赋值
this.itemLeft.push(item)
};
},
Reference Links:Another Vue drag learning reference link: Specific calculation of clientY and other parameters
mousemove
The monitoring effect. After searching for a long time, everyone said that writing a dragglable="true" attribute in HTML would be enough, but it didn't work. Finally, I implemented it in one line of code in js.//去除默认样式 - 避免拖动元素出现禁止图标
e.preventDefault && e.preventDefault();
This article only implements the drag and drop function and records it. I hope that I can achieve perfection when facing similar needs in the future.