JavaScript最常見也最顯著的用途之一是在網頁上添加動畫,從而在視覺上更具有吸引力。其中有翻轉器效果,廣告條應用。記錄兩個實用的示例:
(一)在循環廣告條中添加鏈接
這樣可以讓訪問者通過點擊鏈接進入與廣告相關的站點。
廣告條所需的HTML
<!-- 在循環廣告中添加鏈接 -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banner with Links</title>
<script type="text/javascript" src="script01.js"></script>
</head>
<body bgcolor="#FFFFFF">
<div align="center">
<a href="linkPage.html"><img src="images/banner1.gif" width="400" height="75" id="adBanner" border="0" alt="ad banner" /></a>
</div>
</body>
</html>
以下的js腳本(script01.js)演示如何將循環廣告條轉換爲真正的可點擊的廣告條
window.onload = initBannerLink;
var thisAd = 0;
function initBannerLink() {
if (document.getElementById("adBanner").parentNode.tagName == "A") {
document.getElementById("adBanner").parentNode.onclick = newLocation;
}
//檢查adBanner對象是否包圍在鏈接標籤中,如果是這樣,那麼當點擊鏈接時,將調用newLocation()函數.
rotate();
}
function newLocation() {
var adURL = new Array("negrino.com","sun.com","microsoft.com");
document.location.href = "http://www." + adURL[thisAd];//將當前文檔窗口設置爲文本字符串http://www.加上adURL的的值 return false;//告訴瀏覽器不要再加載這個href,否則會加載URL兩次
}
function rotate() {
var adImages = new Array("images/banner1.gif","images/banner2.gif","images/banner3.gif");
thisAd++;
if (thisAd == adImages.length) {
thisAd = 0;
}
document.getElementById("adBanner").src = adImages[thisAd];
setTimeout(rotate, 3 * 1000);
}
注意:adURL數組中的成員數量必須與adImages數組相同,這個腳本才能正常工作
建一個images文件夾,然後存入banner1.gif,banner2.gif,banner3.gif三張gif格式圖片
(二)隨機開始循環顯示圖像
如果有很多圖片需要顯示,可能不希望在每次加載頁面時都從同樣的圖像開始顯示,下面HTML和js組合可以實現隨機開始
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Random Banner</title>
<script type="text/javascript" src="script02.js"></script>
</head>
<body bgcolor="#FFFFFF">
<div align="center">
<img src="images/spacer.gif" width="400" height="75" id="adBanner" alt="Ad Banner" />
</div>
</body>
</html>
以下js腳本(script02.js)可以從一個隨機圖像開始顯示圖像
window.onload = choosePic;
var adImages = new Array("images/reading1.gif","images/reading2.gif","images/reading3.gif");
var thisAd = 0;
function choosePic() {
thisAd = Math.floor((Math.random() * adImages.length));
document.getElementById("adBanner").src = adImages[thisAd];
rotate();
}
function rotate() {
thisAd++;
if (thisAd == adImages.length) {
thisAd = 0;
}
document.getElementById("adBanner").src = adImages[thisAd];
setTimeout(rotate, 3 * 1000);
}
同樣建立一個images文件夾,加入reading1等三張gif格式圖片。(源《JavaScript基礎教程》)