可以点击这里体验效果:http://keleyi.com/keleyi/phtml/jqtexiao/26.htm

效果图:



代码如下:

 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>jQuery掷色子并显示随机结果-可乐义</title>
 6 <style type="text/css">
 7 #main_keleyi_com{width:800px;margin: 0px auto;}
 8 .demo{width:760px; height:120px; margin:0px auto;}
 9 .wrap{width:90px; height:90px; margin:20px auto 30px auto; position:relative}
10 .dice{width:90px; height:90px; background:url(http://keleyi.com/image/a/hwwnhj7b.png) no-repeat; cursor:pointer;}
11 .dice_1{background-position:-5px -4px}
12 .dice_2{background-position:-5px -107px}
13 .dice_3{background-position:-5px -212px}
14 .dice_4{background-position:-5px -317px}
15 .dice_5{background-position:-5px -427px}
16 .dice_6{background-position:-5px -535px}
17 .dice_t{background-position:-5px -651px}
18 .dice_s{background-position:-5px -763px}
19 .dice_e{background-position:-5px -876px}
20 p#result{text-align:center; font-size:16px}
21 p#result span{font-weight:bold; color:#f30; margin:6px}
22 #dice_mask{width:90px; height:90px; background:#fff; opacity:0; position:absolute; top:0; left:0; z-index:999}
23 </style>
24 <script type="text/javascript" src="http://keleyi.com/keleyi/pmedia/jquery/jquery-1.11.1.min.js"></script>
25 <script type="text/javascript">
26 $(function () {
27 var dice = $("#dice");
28 dice.click(function () {
29 $(".wrap").append("<div id='dice_mask'></div>"); //加遮罩
30 dice.attr("class", "dice"); //清除上次动画后的点数
31 dice.css('cursor', 'default');
32 var num = Math.floor(Math.random() * 6 + 1); //产生随机数1-6
33 dice.animate({ left: '+2px' }, 100, function () {
34 dice.addClass("dice_t");
35 }).delay(200).animate({ top: '-2px' }, 100, function () {
36 dice.removeClass("dice_t").addClass("dice_s");
37 }).delay(200).animate({ opacity: 'show' }, 600, function () {
38 dice.removeClass("dice_s").addClass("dice_e");
39 }).delay(100).animate({ left: '-2px', top: '2px' }, 100, function () {
40 dice.removeClass("dice_e").addClass("dice_" + num);
41 $("#result").html("您掷得点数是<span>" + num + "</span>");
42 dice.css('cursor', 'pointer');
43 $("#dice_mask").remove(); //移除遮罩
44 });
45 });
46 });
47 </script>
48 </head>
49 <body> 
50 <div id="main_keleyi_com">
51 <h2 class="top_title">jQuery掷色子并显示随机结果</h2>
52 请点击色子:
53 
54 <div class="demo">
55 <div class="wrap">
56 <div id="dice" class="dice dice_1"></div>
57 </div>
58 <p id="result">请直接点击上面的色子!</p>
59 </div>
60 <a href="http://keleyi.com/a/bjad/vxywlkah.htm" target="_blank">原文</a>
61 </div>
62 </body>
63 </html>

 

例子中,动画效果是使用jquery的animate函数实现的,请参考:http://keleyi.com/a/bjac/5b62295315de9ace.htm

而用到的Math.floor是取整数,详情请参考:http://keleyi.com/a/bjad/s0ix7ao1.htm

还用到append方法,append() 方法在被选元素的结尾(仍然在内部)插入指定内容,详情请参考http://keleyi.com/a/bjac/0vpch15n.htm

而removeClass方法和addClass方法请参考:http://keleyi.com/a/bjac/e9e40a974de5a902.htm

 

Web前端资源汇总:http://www.cnblogs.com/jihua/p/webfront.html

posted on 2014-08-03 11:19  计划  阅读(4673)  评论(0编辑  收藏  举报