可以通過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>