頁面右側固定懸浮窗(客服、廣告、工具欄),點擊關閉按鈕僅隱藏懸浮窗,不關閉整個瀏覽器窗口。
function guanbi() {
window.close(); // ❌ 關閉當前瀏覽器標籤頁/窗口(需滿足 window.open 打開才生效)
}
<div id="float-panel" class="float-panel">
<div class="panel-content">
<h4>在線客服</h4>
<p>歡迎諮詢...</p>
</div>
<button class="close-btn" onclick="closePanel()">×</button>
</div>
<style>
.float-panel {
position: fixed;
right: 0;
top: 50%;
transform: translateY(-50%);
width: 200px;
background: #fff;
box-shadow: -2px 0 10px rgba(0,0,0,.1);
border-radius: 8px 0 0 8px;
z-index: 9999;
}
.close-btn {
position: absolute;
left: -30px;
top: 0;
width: 30px;
height: 30px;
background: #ff4444;
color: #fff;
border: none;
border-radius: 0 8px 0 0;
cursor: pointer;
}
</style>
function closePanel() {
const panel = document.getElementById('float-panel');
if (panel) {
// 方式 1:完全移除文檔流 (推薦)
panel.style.display = 'none';
// 方式 2:僅隱藏但保留佔位 (可選)
// panel.style.visibility = 'hidden';
// 方式 3:動畫消失後移除 (體驗更好)
// panel.style.opacity = '0';
// panel.style.transition = 'opacity 0.3s';
// setTimeout(() => panel.style.display = 'none', 300);
}
}
function closePanel() {
const panel = document.getElementById('float-panel');
panel.style.display = 'none';
localStorage.setItem('floatPanelClosed', 'true'); // 記錄關閉狀態
}
// 頁面加載時檢查
window.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('floatPanelClosed') === 'true') {
document.getElementById('float-panel').style.display = 'none';
}
});
// 可選:提供「重新顯示」入口 (如 Footer 固定小圖標)
function showPanel() {
document.getElementById('float-panel').style.display = 'block';
localStorage.removeItem('floatPanelClosed');
}
| 錯誤 | 後果 | 修正 |
|---|---|---|
| `window.close()` | 關閉瀏覽器標籤 | 操作目標元素 `style.display='none'` |
| ID 拼寫錯誤 | JS 報錯 `Cannot read property 'style' of null` | 檢查 `id="float-panel"` 與 `getElementById('float-panel')` 一致 |
| 未檢查元素存在 | 單頁應用路由切換元素銷毀後報錯 | `const el = document.getElementById(...); if(el) el.style.display='none'` |
| z-index 過低 | 被其他層級遮擋 | 設置 `z-index: 9999` 確保最上層 |
懸浮窗關閉本質是 DOM 元素隱藏,而非 `window.close()`。掌握 `display/visibility/opacity` 三種隱藏方式差異,配合 `localStorage` 實現用戶偏好記憶,即可構建專業級懸浮交互組件。