jquery動態生成元素並飄落效果

antzone發表於2017-04-12

本章節分享一段程式碼例項,它實現了動態生成元素,並且漸隱漸現飄落效果。

當然此效果可能不見得有什麼實際應用場景,不過可以一個操作DOM元素的例項加以學習。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
.rect {
  background: #DDDDDD;
  width: 100px;
  height: 100px;
  position: absolute;
}
.radius {
  border-radius: 8px;
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
}
.shadow    {
  -moz-box-shadow: -5px -5px 5px #999 inset;
  -webkit-box-shadow: -5px -5px 5px #999 inset;
  box-shadow: -5px -5px 5px #999 inset;
}
#body {
  height: 700px;
  width: 100%;
  background: black;
  margin: 0;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
function createColor() {
  var color = [];
  for (var i = 0; i < 3; i++) {
    color.push(Math.round(Math.random() * 256));
  }
  return "rgb(" + color.join(",") + ")"
}
function createRect(left, top, index) {
  var width = Math.round(Math.random() * 150) + 10;
  var height = Math.round(Math.random() * 150) + 10;
  left = left > width ? left - width : left;
  top = top > height ? top - height : top;
  var html = [];
  html.push('<div id="rect_' + index + '" class="rect shadow radius" style="background:');
  html.push(createColor());
  html.push(';left:');
  html.push(left);
  html.push('px;top:');
  html.push(top);
  html.push('px;width:');
  html.push(width);
  html.push('px; height:');
  html.push(height);
  html.push('px;"></div>');
  return html.join("");
}
 
function initRect() {
  var body = $("#body");
  var width = body.width();
  var height = body.height();
  var index = new Date().getTime();
  body.append(createRect(Math.round(Math.random() * width), Math.round(Math.random() * height), index));
  setAnimate(index, height);
}
 
function setAnimate(index, height) {
  var rect = $("#rect_" + index);
  var top = parseInt(rect.position().top);
  var selfHeight = rect.height();
  if (top > height - selfHeight) {
    rect.remove();
    initRect();
  }
  else {
    var filter = top / height;
    rect.css({ "top": (top + 5) + "px", "opacity": filter });
    setTimeout(function () {
      setAnimate(index, height);
    }, 33);
  }
}
function initAllRect() {
  for (var i = 0; i < 20; i++) {
    initRect();
  }
}
$(document).ready(function () {
  initAllRect();
});
</script>
</head>
<body>
<div id="body" class="shadow radius"></div>
</body>
</html>

相關文章