DIV CSS 佈局教程網

用 jQuery 實作左右對聯廣告
編輯:JQuery特效代碼     

對聯廣告就是頁面左右兩側各貼一張直式圖片,並隨捲動保持在視線內。這個做法在桌機版很常見,實作起來只有幾個重點:視窗寬度判斷、捲動時的位置更新,以及關閉按鈕。

完整程式碼

<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
    var duilian = $("div.duilian");
    var duilian_close = $("a.duilian_close");

    var window_w = $(window).width();
    if (window_w > 1000) { duilian.show(); }

    $(window).scroll(function () {
        var scrollTop = $(window).scrollTop();
        duilian.stop().animate({ top: scrollTop + 100 });
    });

    duilian_close.click(function () {
        $(this).parent().hide();
        return false;
    });
});
</script>
<style>
/* 對聯廣告的樣式 */
.duilian { top: 100px; position: absolute; width: 102px; overflow: hidden; display: none; }
.duilian_left  { left: 6px; }
.duilian_right { right: 6px; }
.duilian_con   { border: red solid 1px; width: 100px; height: 300px; overflow: hidden; }
.duilian_close { width: 100%; height: 24px; line-height: 24px; text-align: center;
                 display: block; font-size: 13px; color: #555555; text-decoration: none; }
</style>
</head>
<body>
<div class="duilian duilian_left">
    <div class="duilian_con">對聯的內容</div>
    <a href="#" class="duilian_close">X 關閉</a>
</div>
<div class="duilian duilian_right">
    <div class="duilian_con">對聯的內容</div>
    <a href="#" class="duilian_close">X 關閉</a>
</div>
<p style="height:1000px;"></p>
</body>
</html>

幾個可以調整的地方

預設 display:none,只有視窗寬度超過 1000px 才顯示,避免在窄螢幕上擋到內容。捲動時用 animate() 做一點緩衝,視覺上比直接設 top 順一些;如果在意效能,也可以改成直接指定 css({ top: ... })。

stop() 那一句是必要的——連續快速捲動時,動畫佇列會堆積,加上 stop() 才不會出現追不上手指的拖影。

關閉目前是兩邊一起收(因為共用同一個 class 選擇器),若要各自獨立關閉,記得改用 $(this).hide() 即可。

希望這篇對大家的 jQuery 開發有幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved