html div可以拖动,如何写
要使HTML的div
元素可拖动,你可以使用原生的JavaScript进行操作。以下是一个简单的示例:
<!DOCTYPE html>
<html>
<body>
<style>
.draggable {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
cursor: move;
}
</style>
<div class="draggable" id="mydiv">
</div>
<script>
// Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
elmnt.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>
</body>
</html>
这个示例中的div
元素可以被用户拖动。当鼠标在元素上按下时,元素开始移动。当鼠标释放时,元素停止移动。
然而,在React中你或许希望使用更现代、更React风格的方法。你可以查看react-draggable库,这是一个专门为React应用提供拖拽功能的库。