vue3+ts div头部标题栏可移动拖拽,且不能超过当前屏幕范围
<div class="botm_year">
<div class="con1_title" @mousedown="(e) => handleRemove(e, 'botm_year')">
<div>标题111,拖拽它即可使整个div移动</div>
</div>
<div class="line_time">
这是内容
</div>
</div>
移动的方法如下,其中dom为需要设置的div,封装此方法可以页面多元素使用
function handleRemove(e: any, doc: any) {
let dom: any = document.getElementsByClassName(doc)[0]
// 鼠标的位置
let x = e.clientX
let y = e.clientY
// 元素的大小
let domW = dom.offsetWidth
let domH= dom.offsetHeight
// 元素的位置
let domLeft = dom.offsetLeft
let domTop= dom.offsetTop
// 窗口大小
let w = window.innerWidth
let h = window.innerHeight
// 鼠标到元素左边距离
let moveX = x - domLeft
let moveY = y - domTop
document.onmousemove = function (e) {
let dropX = w - (e.clientX - moveX) - domW
let dropY = h - (e.clientY - moveY) - domH
if (dropX > w -domW) {
dropX = w - domW
} else if (dropX < 0) {
dropX = 0
}
if (dropY > h - domH- 100) {
dropY = h - domH- 100
} else if (dropY < 0) {
dropY = 0
}
dom.style.right = dropX + 'px'
dom.style.bottom = dropY + 'px'
}
document.onmouseup = function () {
document.onmousemove = null
document.onmouseup = null
}
}
div的样式如下,值得注意的是,设置right还是left ,top还是bottm,必须得和handleRemove方法中的保持一致,因为方法中是设置的right和bottom【dom.style.right = dropX + ‘px’;dom.style.bottom = dropY + ‘px’】,则样式中也得设置right和bottom
.botm_year {
position: fixed;
right: 23vw;
bottom: 50px;
background-color: #fff;
border-radius: 5px;
padding: 5px;
margin-right: 5px;
margin-bottom: 10px;
z-index: 10;
max-width: 60vw;
height: 20vh;
overflow: auto;
}