想在頁面載入後延遲幾秒彈出廣告,再過一陣子自動收起,同時讓使用者可以手動關閉?在 jQuery 中顯示與隱藏元素很簡單,只要用 show 與 hide 即可,而要「定時」則需要搭配 setTimeout 函式。以下分享實作方法。
先在頁面中放入要顯示的廣告區塊:
<div class="toolbarframe" style="display:none;"><a href="https://www.jb51.net" target="_blank"><img src="/upfile/swf/s.jpg" /></a><a class="bigad_close">關閉</a></div>
<script src="/js/jquery-1.7.2.min.js" language="javascript" type="text/javascript"></script>
<script>
$(function(){
setTimeout('$(".toolbarframe").show("slow")',3000);
setTimeout('$(".toolbarframe").hide("slow")',13000);
$(".bigad_close").click(function(){
$(".toolbarframe").hide("slow");
})
});
</script>
setTimeout('$(".toolbarframe").show("slow")',3000); //過三秒 div 慢慢從小到大顯示出來
setTimeout('$(".toolbarframe").hide("slow")',13000); //過十秒再自動把 div 從大到小隱藏
$(".bigad_close").click(function(){
$(".toolbarframe").hide("slow");
})
第一行讓廣告在頁面載入 3 秒後以「slow」動畫效果由小到大展開;第二行讓它在 13 秒後自動由大到小收起;最後一段則綁定關閉按鈕的點擊事件,讓使用者能主動把廣告層關掉。透過 setTimeout 與 show/hide 的動畫參數搭配,就能做出流暢的定時彈出與隱藏效果。