js掷色子并显示随机结果
作者:柯乐义 来源:keleyi.com 发布时间:2014-07-28 查看数:53657
使用JS模拟实现掷色子效果,并显示结果,可以用来做论坛,网站上面的小游戏功能模块,
其实实现这样的JS动画效果的原理很简单的,我们要用到一张图片素材,然后用脚本控制图处的显示位置即可,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery掷色子并显示随机结果</title>
<style type="text/css">
.demo { width: 760px; height: 120px; margin: 10px auto; }
.wrap { width: 90px; height: 90px; margin: 120px auto 30px auto; position: relative; }
.dice { width: 90px; height: 90px; background: url(http://www.jiniannet.com/Attachment/20168) 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="/resources/Script/JQuery.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">
<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>
</div>
</body>
</html>
演示效果:
用到的图片素材:
{width="91" height="915"}
作者:柯乐义 出处:http://keleyi.com/a/bjad/vxywlkah.htm