CSS拖曳盒子案例
以下是一个简单的HTML和CSS代码示例,演示了如何使用CSS创建一个可以被拖动的盒子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖曳盒子</title>
<style>
.draggable-box {
width: 100px;
height: 100px;
background-color: #f0f0f0;
position: absolute;
cursor: move;
}
</style>
</head>
<body>
<div class="draggable-box" id="draggable"></div>
<script>
const draggableBox = document.getElementById('draggable');
draggableBox.addEventListener('mousedown', function(event) {
let shiftX = event.clientX - draggableBox.getBoundingClientRect().left;
let shiftY = event.clientY - draggableBox.getBoundingClientRect().top;
document.addEventListener('mousemove', move);
function move(event) {
draggableBox.style.left = event.clientX - shiftX + 'px';
draggableBox.style.top = event.clientY - shiftY + 'px';
}
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move);
});
});
</script>
</body>
</html>
这段代码中,我们创建了一个可拖动的盒子,通过监听鼠标的mousedown事件来开始拖动操作,计算鼠标点击点与盒子左上角的距离,并在document上注册mousemove事件来更新盒子的位置。鼠标松开时,移除mousemove事件监听。这个示例提供了一个基本的拖曳功能,并且可以在现代浏览器中运行。
评论已关闭