可以通过onmousemove事件来实现拖拽功能,具体步骤如下:
示例代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
#drag {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="drag" onmousedown="drag(event)"></div>
<script>
function drag(event) {
var dragElement = document.getElementById("drag");
var startX = event.clientX - dragElement.offsetLeft;
var startY = event.clientY - dragElement.offsetTop;
document.onmousemove = function(event) {
var newX = event.clientX - startX;
var newY = event.clientY - startY;
dragElement.style.left = newX + "px";
dragElement.style.top = newY + "px";
};
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
};
}
</script>
</body>
</html>