jquery隨機飛舞的小蟲效果

antzone發表於2017-04-18

分享一段程式碼例項,它實現了隨機飛舞的小蟲效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
#bg {
  width: 100%;
  height: 100%;
  position: fixed;
        background-size: cover;
  background-color:black;
}
.xx {
  width: 18px;
        height: 18px;
        position: absolute;
        color: white;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function Fireworm() {
  this.element = $("<div class='xx'>*</div>");
}
Fireworm.prototype.show = function() { //顯示
  this.element.css({
    "top": this.pointY + "px",
    "left": this.pointX + "px"
  })
  $("body").append(this.element);
  return this;
};
 
Fireworm.prototype.newPoint = function() {
  this.pointX = randomInt(window.innerWidth - 100);
  this.pointY = randomInt(window.innerHeight - 100);
  return this;
};
 
Fireworm.prototype.speed = function() { 
  this.speedRun = (randomInt(10) + 5) * 1000;
  return this;
};
 
 
Fireworm.prototype.fly = function() { //飛
  var self = this;
  this.element.animate({
    "top": this.pointY,
    "left": this.pointX
  }, this.speedRun, function() {
    self.speed().newPoint().fly();
  })
};
 
function randomInt(max) {
  return Math.floor(Math.random() * max);
};
 
$(function() {
  var totle = 30;
  var fireworm = [];
  for (var i = 0; i < totle; i++) {
    fireworm[i] = new Fireworm();
    fireworm[i].newPoint().show().speed().newPoint().fly()
  }
})
</script>
</head>
<body>
<div id="bg"></div>
</body>
</html>

相關文章