在拖动结束的地方放置一个元素



我在拖动结束的地方放置元素时遇到了一些问题。我找不到用户放置元素的确切位置(左侧和顶部)。

//html code
<div class="box1">
<div id="item-1" class="item">1</div>
<div id="item-2" class="item" draggable="true" ondragend="dragEnd(event)">2</div>
<div id="item-3" class="item">3</div>
<div id="item-4" class="item">4</div>
</div>
<div id="box-2" class="box2" ondragover="dragOver(event)" ondrop="drop(event)" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"></div>

//javascript code
function dragEnd2(event){
event.target.style.position = "absolute";
let top = ???
let left = ???
event.target.style.top = `${top}px`;
event.target.style.left = `${left}px`;
}

可以通过mousemove事件获取鼠标在event.client.Xevent.client.Y上的位置

const box = document.getElementById('box')
// Define a flag
let isSelectingElement = false;
// Enable dragging for this element on 'mousedown' and 'mouseup'
box.addEventListener('mousedown', function (e) {
isSelectingElement = true;
})
box.addEventListener('mouseup', function (e) {
isSelectingElement = false;
})
// Get mouse X and Y position and update element position based on that
document.addEventListener('mousemove', function (e) {
if (isSelectingElement) {
box.style.top = `${e.clientY}px`
box.style.left = `${e.clientX}px`
}
})
#box {
width: 50px;
height: 50px;
background-color: blueviolet;
position: absolute;
}
<body>
<div id="box" class="box"></div>
</body>

相关内容

  • 没有找到相关文章

最新更新