傳統 iframe 架構聊天室:父視窗包含輸入表單,子視窗 (iframe name="d") 顯示訊息區。需求:訊息區新增內容時自動捲動到底部;使用者手動捲動查看歷史時暫停自動捲動,重新聚焦輸入框恢復。
<script>
// 狀態旗標
let autoScroll = true;
let scrollTimer = null;
// 監聽父視窗表單的 checkbox 控制 (假設父視窗有 name="as" 的 checkbox)
function syncAutoScroll() {
try {
const chk = parent.document.inputform.as;
autoScroll = chk.checked;
} catch (e) {
// 跨域或結構不同靜默忽略
}
}
// 核心捲動函數
function scrollToBottom() {
if (!autoScroll) return;
// 直接捲動到極大值確保到底
window.scrollTo(0, document.body.scrollHeight);
// 200ms 輪詢 (適應新訊息追加)
scrollTimer = setTimeout(scrollToBottom, 200);
}
// 事件綁定:失焦恢復自動捲動、聚焦暫停
window.onblur = () => { autoScroll = true; scrollToBottom(); };
window.onfocus = () => { autoScroll = false; };
// 啟動
scrollToBottom();
// 供父視窗呼叫 (新訊息到達時強制觸發)
window.forceScroll = scrollToBottom;
</script>
<form name="inputform" action="send.php" method="post" target="d">
<input type="text" name="msg" />
<input type="submit" value="送出" />
<label><input type="checkbox" name="as" checked> 自動捲動</label>
</form>
<iframe name="d" src="chat_view.php"></iframe>
<div id="messages" style="height:300px; overflow-y:auto;">...</div>
<script>
const msgBox = document.getElementById('messages');
let userScrolled = false;
msgBox.addEventListener('scroll', () => {
// 判斷是否已在底部 (容差 50px)
const atBottom = msgBox.scrollTop + msgBox.clientHeight >= msgBox.scrollHeight - 50;
userScrolled = !atBottom;
});
function appendMessage(html) {
msgBox.insertAdjacentHTML('beforeend', html);
if (!userScrolled) {
msgBox.scrollTop = msgBox.scrollHeight; // 平滑捲動可用 scrollTo({top, behavior:'smooth'})
}
}
// WebSocket/AJAX 推送新訊息時呼叫 appendMessage()
</script>
| 特性 | 舊版 iframe + 輪詢 | 現代單頁 + 事件驅動 |
|---|---|---|
| 捲動觸發 | 定時器 200ms | 新訊息到達時立即 |
| 使用者干擾檢測 | 焦點事件 (粗略) | scroll 事件精準判斷是否離底 |
| 跨域限制 | 易受同源策略阻擋 | 同源無問題 |
| 程式碼複雜度 | 低 | 中 (需狀態管理) |
自動捲動核心在於「偵測使用者意圖」:主動捲動閱讀歷史 = 暫停;新訊息到達且使用者在底部 = 立即捲動。現代寫法以 scroll 事件精準判斷,體驗更順暢,且擺脫 iframe 跨域框架限制。