H5 页面拖动悬浮按钮
要在H5页面中实现拖动悬浮按钮,你可以使用JavaScript监听鼠标事件来更新按钮的位置。以下是一个简单的实现示例:
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draggable Button</title>
<style>
#floatButton {
position: absolute;
width: 50px;
height: 50px;
background-color: #007bff;
color: white;
border-radius: 50%;
text-align: center;
line-height: 50px;
cursor: pointer;
user-select: none;
}
</style>
</head>
<body>
<div id="floatButton">+</div>
<script src="script.js"></script>
</body>
</html>
JavaScript部分 (script.js):
let isDragging = false;
let dragButton = document.getElementById('floatButton');
dragButton.addEventListener('mousedown', function(e) {
isDragging = true;
offsetX = e.clientX - dragButton.offsetLeft;
offsetY = e.clientY - dragButton.offsetTop;
});
window.addEventListener('mouseup', function() {
isDragging = false;
});
window.addEventListener('mousemove', function(e) {
if (isDragging) {
dragButton.style.left = (e.clientX - offsetX) + 'px';
dragButton.style.top = (e.clientY - offsetY) + 'px';
}
});
这段代码会让页面中的圆形按钮可以被拖动。当鼠标点击按钮时,mousedown
事件会被触发,并开始跟踪鼠标移动。在鼠标移动时,mousemove
事件会更新按钮的位置。当鼠标松开时,mouseup
事件会停止拖动操作。
评论已关闭