html可移动的悬浮按钮,js仿苹果悬浮可拖拽按钮,并且点击展开效果
时间: 2023-07-23 21:26:34 浏览: 353
android 应用内部悬浮可拖动按钮简单实现代码
要实现一个可移动的悬浮按钮,并且点击后有展开效果,可以使用 HTML、CSS 和 JavaScript。下面是一个简单的示例代码:
HTML 代码:
```
<div id="floatBtn">
<div class="btn-icon">按钮</div>
<div class="btn-panel">
<ul>
<li>选项一</li>
<li>选项二</li>
<li>选项三</li>
</ul>
</div>
</div>
```
CSS 代码:
```
#floatBtn {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 9999;
}
.btn-icon {
background-color: #4CAF50;
color: white;
border: none;
border-radius: 50%;
padding: 15px;
font-size: 24px;
cursor: pointer;
}
.btn-panel {
display: none;
position: absolute;
bottom: 70px;
right: 0;
background-color: white;
border: 1px solid #ccc;
padding: 10px;
}
.btn-panel ul {
list-style: none;
margin: 0;
padding: 0;
}
.btn-panel ul li {
padding: 5px;
cursor: pointer;
}
.btn-panel ul li:hover {
background-color: #f5f5f5;
}
```
JavaScript 代码:
```
var floatBtn = document.getElementById("floatBtn");
var btnIcon = floatBtn.querySelector(".btn-icon");
var btnPanel = floatBtn.querySelector(".btn-panel");
// 点击按钮展开/收起面板
btnIcon.addEventListener("click", function() {
if (btnPanel.style.display === "none") {
btnPanel.style.display = "block";
} else {
btnPanel.style.display = "none";
}
});
// 拖拽按钮
var isDragging = false;
var offsetX = 0;
var offsetY = 0;
btnIcon.addEventListener("mousedown", function(e) {
isDragging = true;
offsetX = e.clientX - floatBtn.offsetLeft;
offsetY = e.clientY - floatBtn.offsetTop;
});
document.addEventListener("mousemove", function(e) {
if (isDragging) {
var x = e.clientX - offsetX;
var y = e.clientY - offsetY;
floatBtn.style.left = x + "px";
floatBtn.style.top = y + "px";
}
});
document.addEventListener("mouseup", function() {
isDragging = false;
});
```
这段代码实现了一个在页面右下角的悬浮按钮,点击按钮可以展开一个带有选项的面板,同时也实现了可拖拽的效果。
阅读全文