写一个可以使用鼠标拖动的div
时间: 2024-05-21 08:10:53 浏览: 12
<!DOCTYPE html>
<html>
<head>
<title>Draggable Div</title>
<style>
#draggable {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
}
</style>
</head>
<body>
<div id="draggable"></div>
<script>
var draggable = document.getElementById('draggable');
var isDragging = false;
var mouseOffset = {x: 0, y: 0};
draggable.addEventListener('mousedown', function(event) {
isDragging = true;
mouseOffset.x = event.offsetX;
mouseOffset.y = event.offsetY;
});
draggable.addEventListener('mousemove', function(event) {
if (isDragging) {
draggable.style.left = event.pageX - mouseOffset.x + 'px';
draggable.style.top = event.pageY - mouseOffset.y + 'px';
}
});
draggable.addEventListener('mouseup', function(event) {
isDragging = false;
});
</script>
</body>
</html>
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)