jquery實現圖片隨機切換、抽獎功能
效果圖:
源代碼:
HTML:
<body>
<!-- 小像框 -->
<div id="div1">
<img id="xiaoImgID" src="img/mei0.jpg">
</div>
<!-- 開始按鈕 -->
<input id="startID" type="button" value="開始">
<!-- 停止按鈕 -->
<input id="stopID" type="button" value="停止">
<!-- 大像框 -->
<div id="div2">
<img id="daImgID" src="img/mei0.jpg">
</div>
</body>
CSS:
<style>
div{float: left;}
#div1{border:2px #0f0f0f solid; width: 100px; height: 165px; margin-left: 50px; margin-left: 100px;}
#div2{border:2px #0f0f0f solid; width: 400px; height: 650px; margin-left: 600px;}
#xiaoImgID{ width: 100px; height: 165px;}
#daImgID{width: 400px; height: 650px;}
#startID{width: 100px; height: 80px; font-size: 22px; margin-left: 100px;}
#stopID{width: 100px; height: 80px; font-size: 22px; margin-left: 30px;}
</style>
jquery:
<script>
var startID;
var index;
$(function () {
// 2.給按鈕添加單擊事件
$("#startID").click(function () {
// 用戶每次點擊開始按鈕時先關閉一次定時器
// 防止用戶多次點擊開始按鈕造成的同時運行多個定時器的bug
clearInterval(startID);
// 2.1定義一個循環定時器 30毫秒循環一次
startID = setInterval(function () {
// 2.2生成隨機角標 0-6 floor向下取整
index = Math.floor(Math.random() * 7);
// 2.3設置小像框的src屬性
$("#xiaoImgID").prop("src","img/mei" + index + ".jpg");
},60);
});
// 3.點擊停止按鈕 結束定時器
$("#stopID").click(function () {
// 3.1停止定時器
clearInterval(startID);
// 3.2給大像框設置src屬性 .hide()先把大像框裏的圖片去掉
$("#daImgID").prop("src","img/mei" + index + ".jpg").hide();
// 3.3秒後顯示
$("#daImgID").fadeIn(1500);
});
});
</script>