以下是 jQuery实现重力模拟效果js代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>jQuery</title>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' />
<link href='css/style.css' rel='stylesheet' type='text/css' />
<script src="js/jquery-1.9.1.js" type="text/javascript"></script>
<script src="js/jquery.easing.1.3.js" type="text/javascript"></script>
<link href='css/gravity.css' rel='stylesheet' type='text/css' />
<script src="js/gravity.js" type="text/javascript"></script>
</head>
<body>
<div style='padding: 15px;'>
<div class='content'>
<h2>Example:</h2>
<div id="air">
<div style='padding-left: 100px;' class="block_container">
<div class="block">
Block 1
</div>
<div class='handle_wrap'>
<div class="handle">
</div>
</div>
<div class="block">
Block 2
</div>
</div>
<div style='padding-left: 100px' class='block_container'>
<div class="block">
Block 3
</div>
<div class='handle_wrap'>
<div class="handle">
</div>
</div>
<div class="block">
Block 4
</div>
</div>
<div style='padding-left: 100px' class='block_container'>
<div class="block">
Block 5
</div>
<div class='handle_wrap'>
<div class="handle">
</div>
</div>
<div class="block">
Block 6
</div>
</div>
</div>
<div id="ground">
</div>
<br />
</div>
</div>
</body>
</html>
JS代码(gravity.js):
var Gravity ={
init:function(){
$("#air .block_container").css({
height:$("#air").outerHeight() + "px"}
);
$(".handle").mouseenter(function(i){
//animate the cutting of the string$(this).animate({
height:"20px"}
,{
duration:1500,easing:"easeOutElastic"}
);
var block = $(this).parent().next();
var yposBlock = $(block).position()['top'] - $("#air").position()['top'];
var fallDist = ($("#air").outerHeight() - yposBlock) - $(block).outerHeight();
//let the block fall$(block).stop().animate({
marginTop:fallDist+"px"}
,{
duration:1000,easing:"easeOutBounce"}
);
}
);
}
,reset:function(){
$(".handle").stop().animate({
height:"50px"}
,{
duration:1000,easing:"easeInElastic"}
);
$(".block").stop().animate({
marginTop:"0px"}
,{
duration:1000,easing:"easeInBounce"}
);
}
}
$(document).ready(function(){
Gravity.init();
}
);
CSS代码(gravity.css):
.block{padding:20px;background-color:black;color:white;width:100px;text-align:center;}
.handle{width:4px;height:50px;background-color:red;cursor:pointer;margin-left:68px;}
.handle_wrap{height:50px;}
#air{height:500px;padding-top:20px;background-color:#B4D7F4;}
.block_container{float:left;width:140px;}
#ground{padding:20px;background-color:#5F3800;color:white;}
CSS代码(style.css):
body{font-size:10px;font-family:verdana,sans-serif;background-color:gray;padding:0px;margin:0px;}
.content{width:800px;margin:0px auto;background-color:#ffffff;padding:20px;}
h1{color:#221A69;font-weight:normal;text-decoration:none;}