js实现浮动窗口
浮动窗口的基本实现
使用HTML和CSS创建浮动窗口结构:
<div id="floatWindow" style="display:none; position:fixed; width:300px; height:200px; background:#fff; border:1px solid #ccc; z-index:1000;">
<div style="padding:10px;">
<span id="closeBtn" style="float:right; cursor:pointer;">×</span>
<h3>浮动窗口标题</h3>
<p>这里是浮动窗口内容</p>
</div>
</div>
JavaScript控制显示和隐藏:
// 显示浮动窗口
function showFloatWindow() {
document.getElementById('floatWindow').style.display = 'block';
}
// 隐藏浮动窗口
function hideFloatWindow() {
document.getElementById('floatWindow').style.display = 'none';
}
// 绑定关闭按钮
document.getElementById('closeBtn').addEventListener('click', hideFloatWindow);
可拖拽功能实现
为浮动窗口添加拖拽功能:
let isDragging = false;
let offsetX, offsetY;
const floatWindow = document.getElementById('floatWindow');
floatWindow.addEventListener('mousedown', (e) => {
if (e.target === floatWindow || e.target.parentNode === floatWindow) {
isDragging = true;
offsetX = e.clientX - floatWindow.getBoundingClientRect().left;
offsetY = e.clientY - floatWindow.getBoundingClientRect().top;
}
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
floatWindow.style.left = (e.clientX - offsetX) + 'px';
floatWindow.style.top = (e.clientY - offsetY) + 'px';
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
响应式定位
确保浮动窗口在不同屏幕尺寸下保持可见:
function positionFloatWindow() {
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const floatWidth = floatWindow.offsetWidth;
const floatHeight = floatWindow.offsetHeight;
floatWindow.style.left = (windowWidth - floatWidth) / 2 + 'px';
floatWindow.style.top = (windowHeight - floatHeight) / 3 + 'px';
}
window.addEventListener('resize', positionFloatWindow);
positionFloatWindow();
动画效果增强
为浮动窗口添加平滑的显示动画:
#floatWindow {
transition: all 0.3s ease;
transform: translateY(-20px);
opacity: 0;
}
#floatWindow.show {
transform: translateY(0);
opacity: 1;
}
function showWithAnimation() {
const floatWindow = document.getElementById('floatWindow');
floatWindow.classList.add('show');
floatWindow.style.display = 'block';
setTimeout(() => {
floatWindow.style.transform = 'translateY(0)';
floatWindow.style.opacity = '1';
}, 10);
}
浏览器兼容性处理
处理旧版本浏览器的兼容性问题:

// 事件监听兼容性处理
function addEvent(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + event, handler);
} else {
element['on' + event] = handler;
}
}
// 获取样式兼容性处理
function getStyle(element, property) {
return window.getComputedStyle
? window.getComputedStyle(element, null).getPropertyValue(property)
: element.currentStyle[property];
}






