DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery常見問題 >> jQuery擲色子並顯示隨機結果
jQuery擲色子並顯示隨機結果
編輯:JQuery常見問題     
效果如下:

jQuery擲色子並顯示隨機結果:

請直接點擊上面的色子!



也可以點擊這裡體驗效果:http:///keleyi/phtml/jqtexiao/26.htm

代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery擲色子並顯示隨機結果-可樂義</title>
<style type="text/css">
#main_keleyi_com{width:800px;margin: 0px auto;}
.demo{width:760px; height:120px; margin:0px auto;}
.wrap{width:90px; height:90px; margin:20px auto 30px auto; position:relative}
.dice{width:90px; height:90px; background:url(http:///image/a/hwwnhj7b.png) no-repeat; cursor:pointer;}
.dice_1{background-position:-5px -4px}
.dice_2{background-position:-5px -107px}
.dice_3{background-position:-5px -212px}
.dice_4{background-position:-5px -317px}
.dice_5{background-position:-5px -427px}
.dice_6{background-position:-5px -535px}
.dice_t{background-position:-5px -651px}
.dice_s{background-position:-5px -763px}
.dice_e{background-position:-5px -876px}
p#result{text-align:center; font-size:16px}
p#result span{font-weight:bold; color:#f30; margin:6px}
#dice_mask{width:90px; height:90px; background:#fff; opacity:0; position:absolute; top:0; left:0; z-index:999}
</style>
<script type="text/javascript" src="http:///keleyi/pmedia/jquery/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
var dice = $("#dice");
dice.click(function () {
$(".wrap").append("<div id='dice_mask'></div>"); //加遮罩
dice.attr("class", "dice"); //清除上次動畫後的點數
dice.css('cursor', 'default');
var num = Math.floor(Math.random() * 6 + 1); //產生隨機數1-6
dice.animate({ left: '+2px' }, 100, function () {
dice.addClass("dice_t");
}).delay(200).animate({ top: '-2px' }, 100, function () {
dice.removeClass("dice_t").addClass("dice_s");
}).delay(200).animate({ opacity: 'show' }, 600, function () {
dice.removeClass("dice_s").addClass("dice_e");
}).delay(100).animate({ left: '-2px', top: '2px' }, 100, function () {
dice.removeClass("dice_e").addClass("dice_" + num);
$("#result").html("您擲得點數是<span>" + num + "</span>");
dice.css('cursor', 'pointer');
$("#dice_mask").remove(); //移除遮罩
});
});
});
</script>
</head>
<body>
<div id="main_keleyi_com">
<h2 class="top_title">jQuery擲色子並顯示隨機結果</h2>
請點擊色子:

<div class="demo">
<div class="wrap">
<div id="dice" class="dice dice_1"></div>
</div>
<p id="result">請直接點擊上面的色子!</p>
</div>
<a href="http:///a/bjad/vxywlkah.htm" target="_blank">原文</a>
</div>
</body>
</html>

例子中,動畫效果是使用jquery的animate函數實現的,請參考:http:///a/bjac/5b62295315de9ace.htm

而用到的Math.floor是取整數,詳情請參考:http:///a/bjad/s0ix7ao1.htm

還用到append方法,append() 方法在被選元素的結尾(仍然在內部)插入指定內容,詳情請參考http:///a/bjac/0vpch15n.htm

而removeClass方法和addClass方法請參考:http:///a/bjac/e9e40a974de5a902.htm
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved