css制作一个悬浮在浏览器上的可拖动挂件
时间: 2024-02-20 10:00:03 浏览: 26
要制作一个悬浮在浏览器上的可拖动挂件,需要用到CSS的position属性、z-index属性和JavaScript的drag事件。以下是一个简单的例子:
HTML代码:
```
<div class="widget" draggable="true">
<p>这是一个可拖动挂件</p>
</div>
```
CSS代码:
```
.widget {
position: fixed;
top: 50px;
right: 50px;
z-index: 9999;
background-color: #fff;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
padding: 10px;
border-radius: 5px;
}
```
JavaScript代码:
```
const widget = document.querySelector('.widget');
let isDragging = false;
let lastX = 0;
let lastY = 0;
widget.addEventListener('mousedown', (e) => {
lastX = e.clientX;
lastY = e.clientY;
isDragging = true;
});
widget.addEventListener('mouseup', () => {
isDragging = false;
});
widget.addEventListener('mousemove', (e) => {
if (isDragging) {
const deltaX = e.clientX - lastX;
const deltaY = e.clientY - lastY;
const newX = parseInt(widget.style.right) - deltaX;
const newY = parseInt(widget.style.top) + deltaY;
widget.style.right = newX + 'px';
widget.style.top = newY + 'px';
lastX = e.clientX;
lastY = e.clientY;
}
});
```
解释一下代码:
- `draggable="true"` 属性使挂件可拖动。
- `mousedown` 事件监听鼠标按下事件,记录当前鼠标位置并将 `isDragging` 标志设为 true。
- `mouseup` 事件监听鼠标松开事件,将 `isDragging` 标志设为 false。
- `mousemove` 事件监听鼠标移动事件,当 `isDragging` 为 true 时,计算鼠标移动的距离,更新挂件的位置,并更新记录的鼠标位置。
这样就可以实现一个悬浮在浏览器上的可拖动挂件了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)