js es6实现动态悬浮窗
时间: 2023-07-18 20:09:03 浏览: 69
实现动态悬浮窗,需要用到JavaScript的DOM操作和CSS的定位样式。下面是一个简单的实现方式:
首先在HTML中添加一个悬浮窗的div元素,设置其样式为绝对定位,并设置初始位置和大小。
```html
<div id="float-window" style="position: absolute; top: 100px; left: 100px; width: 200px; height: 200px; background-color: #FFF;"></div>
```
然后在JavaScript中获取该元素,并添加鼠标事件监听器,实现拖拽功能。拖拽时需要计算鼠标在悬浮窗内的位置,以保持悬浮窗与鼠标的相对位置不变。
```javascript
const floatWindow = document.getElementById('float-window');
let isDragging = false;
let mouseOffsetX = 0;
let mouseOffsetY = 0;
floatWindow.addEventListener('mousedown', (event) => {
isDragging = true;
mouseOffsetX = event.clientX - floatWindow.offsetLeft;
mouseOffsetY = event.clientY - floatWindow.offsetTop;
});
document.addEventListener('mousemove', (event) => {
if (isDragging) {
floatWindow.style.left = event.clientX - mouseOffsetX + 'px';
floatWindow.style.top = event.clientY - mouseOffsetY + 'px';
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
```
最后,可以在需要显示悬浮窗的时候,将其添加到文档中,即可实现动态悬浮窗的效果。
```javascript
document.body.appendChild(floatWindow);
```