ASP.NET 預設頁面包含 XHTML 1.0 Transitional DOCTYPE,觸發瀏覽器標準模式,導致 document.body.scrollTop 永遠為 0,漂浮圖片失效。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
document.body.scrollTop 有效**。document.documentElement.scrollTop (即 <html> 元素) 有效**,body.scrollTop 固定 0。function getScrollTop() {
return document.documentElement.scrollTop || document.body.scrollTop || 0;
}
function getScrollLeft() {
return document.documentElement.scrollLeft || document.body.scrollLeft || 0;
}
// 漂浮圖片邏輯
function floatImage() {
var img = document.getElementById('floatImg');
var top = getScrollTop() + 100; // 距離頂部 100px
var left = getScrollLeft() + document.documentElement.clientWidth - img.offsetWidth - 20;
img.style.top = top + 'px';
img.style.left = left + 'px';
}
window.onscroll = floatImage;
window.onresize = floatImage;
<style>
.float-image {
position: fixed;
top: 100px;
right: 20px;
z-index: 9999;
}
</style>
<img id="floatImg" class="float-image" src="float.png" alt="漂浮圖片" />
ClientIDMode="Static" 或使用 ClientID 取得正確 ID。ScriptManager / Page.ClientScript.RegisterClientScriptBlock 註冊腳本,避免重複註冊。拥抱標準模式 + CSS Fixed,徹底解決漂浮定位相容性難題。