這款對聯廣告與常見版本有點不同:頁面載入時看不到廣告,接著它會從左右兩側「飛」進來,並持續以緩動效果貼齊視窗邊緣。核心概念是搭配 setInterval 做位移插值。
<style type="text/css">
.shuoming { margin-top:20px; border:1px solid #ccc; padding-bottom:10px;
width:600px; margin:0 auto; }
.shuoming dt { height:30px; line-height:30px; font-weight:bold; text-indent:10px; }
.shuoming dd { line-height:20px; padding:5px 20px; }
</style>
<script language="JavaScript">
var delta = 0.08; // 緩動係數,數值越小移動越慢
var collection;
function floaters() {
this.items = [];
this.addItem = function (id, x, y, content) {
document.write('<DIV id=' + id +
' style="Z-INDEX: 10; POSITION: absolute; width:80px; height:60px;left:' +
(typeof (x) == 'string' ? eval(x) : x) + ';top:' +
(typeof (y) == 'string' ? eval(y) : y) + '">' + content + '</DIV>');
var newItem = {};
newItem.object = document.getElementById(id);
newItem.x = x;
newItem.y = y;
this.items[this.items.length] = newItem;
};
this.play = function () {
collection = this.items;
setInterval('play()', 10);
};
}
function play() {
for (var i = 0; i < collection.length; i++) {
var followObj = collection[i].object;
var followObj_x = (typeof (collection[i].x) == 'string' ? eval(collection[i].x) : collection[i].x);
var followObj_y = (typeof (collection[i].y) == 'string' ? eval(collection[i].y) : collection[i].y);
// 水平方向:逐步逼近目標位置
if (followObj.offsetLeft != (document.documentElement.scrollLeft + followObj_x)) {
var dx = (document.documentElement.scrollLeft + followObj_x - followObj.offsetLeft) * delta;
dx = (dx > 0 ? 1 : -1) * Math.ceil(Math.abs(dx));
followObj.style.left = followObj.offsetLeft + dx;
}
// 垂直方向:同理
if (followObj.offsetTop != (document.documentElement.scrollTop + followObj_y)) {
var dy = (document.documentElement.scrollTop + followObj_y - followObj.offsetTop) * delta;
dy = (dy > 0 ? 1 : -1) * Math.ceil(Math.abs(dy));
followObj.style.top = followObj.offsetTop + dy;
}
followObj.style.display = '';
}
}
var theFloaters = new floaters();
// 右側
theFloaters.addItem('followDiv1', 'document.documentElement.clientWidth-106', 80,
'<img src=https://pic.jb51.net/sudu.gif id=ad />');
// 左側
theFloaters.addItem('followDiv2', 6, 80,
'<img src=https://pic.jb51.net/sudu.gif id=ad />');
theFloaters.play();
</script>
如果要讓圖片可點擊,把內容換成連結即可:
<a href="https://www.jb51.net/" target="_blank"> <img src="https://pic.jb51.net/sudu.gif" border="0"> </a>
每次 play() 被觸發時,程式會計算「元素目前位置」與「目標位置」的差距,乘以 delta 得到這一步該走多少,再用 Math.ceil 確保至少移動 1 像素,避免無限逼近卻永遠到不了終點。這就是所謂的「緩動」(easing)效果。
這份程式寫於較早的年代,有幾點值得改良:eval 的字串寫法可以用函式取代;setInterval('play()', 10) 的字串形式應改為直接傳函式參照;document.write 在頁面載入後呼叫會清空整個文件,建議改用 createElement。另外,廣告若遮住主要內容或無法關閉,會影響使用體驗,實務上務必加上關閉按鈕,並遵守相關法規與平台政策。