1. 程式人生 > >18. jQuery-使用function()函式隨機展示圖片

18. jQuery-使用function()函式隨機展示圖片

1. 效果圖

在這裡插入圖片描述

2. html程式碼

<!DOCTYPE html>
<html>
<head>
    <title>jQuery-使用function()函式隨機展示圖片</title>
        <style type="text/css">
           body{font-size:12px}
           .clsSpn{float:left;padding-top:10px;padding-left:10px}
           .clsImg{border:solid 1px #ccc;padding:3px;float:left}
    	</style>
</head>
<body>
      <img alt="" style="float:left" width="70px;" height="70px;" src="../img/img03.jpg"/>
      
<script src="../jquery.min.js"></script>
<script type="text/javascript">
	$(function(){
		window.setInterval(refreshImg, 1000);

		//設定title屬性
		$("img").attr("title", "這是一隻會變身的小豬");

		//增加樣式
		$("img").addClass("clsImg");
	})
	
	function refreshImg() {
		//設定src屬性
		$("img").attr("src", function(){
			console.log(Math.floor(Math.random()*2+1));
			return "../img/img0"+Math.floor(Math.random()*2+1)+".jpg";
		});
	}
</script>
</body>
</html>