只要具備一定的 JavaScript 基礎,制作浮動廣告其實並不難。所謂浮動廣告,就是當頁面滾動時,廣告圖與關閉按鈕始終懸浮在頁面右側固定位置。下面直接上代碼:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#csdn {
width: 800px;
margin: 0 auto;
}
#ad {
position: absolute;
right: 0px;
top: 30px;
z-index: 1;
}
#cl {
position: absolute;
right: 0px;
top: 30px;
z-index: 2;
}
</style>
<script type="text/javascript">
var advInitTop = 30;
var closeInitTop = 30;
function inix() {
advInitTop = document.getElementById("ad").style.pixelTop;
closeInitTop = document.getElementById("cl").style.pixelTop;
}
function closeAd() {
document.getElementById("ad").style.display = "none";
document.getElementById("cl").style.display = "none";
}
function move() {
document.getElementById("ad").style.pixelTop = document.documentElement.scrollTop + advInitTop;
document.getElementById("cl").style.pixelTop = document.documentElement.scrollTop + closeInitTop;
window.status = document.documentElement.scrollTop + "/" + document.getElementById("ad").style.pixelTop;
}
window.onscroll = move;
</script>
</head>
<body>
<div id="cl" onclick="closeAd()">
<img src="images/close.jpg" />
</div>
<div id="csdn">
<a href="https://www.csdn.net"><img src="images/xiaojie1.jpg" border="0" /></a>
</div>
<div id="ad">
<a href="https://www.taobao.com"><img src="images/advpic.gif" /></a>
</div>
</body>
</html>
要點:
核心在於 move 函數:它綁定在 window.onscroll 上,每次頁面滾動時,把廣告層 #ad 與關閉按鈕層 #cl 的頂部位置重新設置為「當前滾動距離 + 初始偏移」,從而使它們相對於視覺保持固定,達到浮動的效果。
需要特別注意的是,代碼中要用 document.documentElement.scrollTop,而不要用老式的 document.body.scrollTop,否則不符合 W3C 標準,在標準模式下可能看不到浮動效果。