點一下按鈕就換一張圖,是 banner 輪播最簡陋的前身。核心只有一句:Math.random() 產生亂數,再用 attr('src', ...) 換掉圖片路徑。
<!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>
<title></title>
<style type="text/css">
img {
width: 200px;
height: 200px;
}
</style>
<script src="jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#btn1').click(function () {
var num = Math.floor(Math.random() * 8 + 1);
$('img').attr('src', 'picture/' + num + '.jpg');
});
});
</script>
</head>
<body>
<img src="picture/1.jpg" id="img1" />
<input id="btn1" type="button" value="變換" />
</body>
</html>
Math.random() 回傳 0(含)到 1(不含)之間的小數,因此:
Math.random() * 8 得到 0 ~ 7.999…+ 1 後變成 1 ~ 8.999…Math.floor() 無條件捨去,最終得到 1 到 8 的整數。對應到 picture/1.jpg ~ picture/8.jpg,剛好八張圖。
第一,目前有可能連續兩次抽到同一張,視覺上像沒反應。加一個判斷即可避開:
var num;
do {
num = Math.floor(Math.random() * 8 + 1);
} while (num === lastNum);
lastNum = num;
第二,$('img') 會選到頁面上所有圖片,如果日後版面加了 logo 就會誤傷。給目標圖片一個 id 並改寫成 $('#img1'),是更安全的習慣。若想避免圖片切換時閃白,也可以先把八張圖預載到暫存記憶體再切換。