要使用JavaScript和CSS创建可拖动的HTML元素,代码如下-
<!DOCTYPE html>
<html>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.dragDiv {
position: absolute;
z-index: 9;
text-align: center;
border: 1px solid #d3d3d3;
padding: 30px;
cursor: move;
z-index: 10;
background-color: rgb(108, 24, 177);
color: #fff;
font-size: 20px;
font-weight: 500;
}
</style>
<body>
<h1>Draggable DIV Element Example</h1>
<h2>Click and drag the below element to move it around</h2>
<div class="dragDiv">
This div can be moved around
</div>
<script>
dragElement(document.querySelector(".dragDiv"));
function dragElement(ele) {
var pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (document.querySelector(ele.id + "header")) {
document.getElementById(
ele.id + "header"
).onmousedown = dragMouseDown;
}
else {
ele.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
ele.style.top = ele.offsetTop - pos2 + "px";
ele.style.left = ele.offsetLeft - pos1 + "px";
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>
</body>
</html>
输出结果
上面的代码将产生以下输出-
通过拖动来移动div时-