jquery投色子动画

时间:2023-03-09 02:25:45
jquery投色子动画

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

效果图:

jquery投色子动画

代码如下:

 <!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://keleyi.com/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.com/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://keleyi.com/a/bjad/vxywlkah.htm" target="_blank">原文</a>
</div>
</body>
</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