js煙花效果程式碼例項

admin發表於2017-04-15

分享一段程式碼例項,它實現了煙花效果。

點選頁面會有燃放煙花的效果,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
body {
  background: black;
  overflow: hidden;
}
div {
  position: absolute;
}
</style>
</head>
<body>
<script type="text/javascript">
function rgb() { //建立顏色隨機值
  var str = Math.ceil(Math.random() * 16777215).toString(16);
  while (str.length < 6) {
    str = '0' + str;
  }
  return str;
}
document.onclick = function(event) {
  var oEvent = event || window.event;
  var t = oEvent.clientY;
  var l = oEvent.clientX;
  var oRdeDiv = document.createElement('div'); //建立一個div
  oRdeDiv.style.width = '4px';
  oRdeDiv.style.height = '30px';
  oRdeDiv.style.background = 'red';
  document.body.appendChild(oRdeDiv); //向body新增一個div元素
  oRdeDiv.style.top = document.documentElement.clientHeight + 'px';
  oRdeDiv.style.left = oEvent.clientX + 'px';
  //alert(oRdeDiv.offsetTop)
  var timer = setInterval(function() { //讓建立的這個div從下往上打上來!
    oRdeDiv.style.top = oRdeDiv.offsetTop - 20 + 'px';
    if (oRdeDiv.offsetTop <= t) {
      clearInterval(timer);
      document.body.removeChild(oRdeDiv);
      var i = 0;
      var aDiv = [];
      for (var i = 0; i < 50; i++) { //建立多個div
        var oDiv = document.createElement('div');
        oDiv.style.background = '#' + rgb();
        oDiv.style.width = '2px';
        oDiv.style.height = '2px';
        oDiv.style.left = l + 'px';
        oDiv.style.top = t + 'px';
        document.body.appendChild(oDiv);
        aDiv.push(oDiv);
        oDiv.speedX = Math.random() * 20 - 10; //新增一個x軸的速度
        oDiv.speedY = Math.random() * 20 - 10; //新增一個y軸的速度
 
      }
      var newtimer = setInterval(function() { //讓每個div隨機往下掉,以達到煙花效果
        var count = 0;
        for (var i = 0; i < aDiv.length; i++) {
          if (!aDiv[i]) continue; //當aDiv[i]為空不再進行迴圈操作
          aDiv[i].style.left = aDiv[i].offsetLeft + aDiv[i].speedX + 'px';
          aDiv[i].style.top = aDiv[i].offsetTop + aDiv[i].speedY + 'px';
          aDiv[i].speedY++; //y軸的速度越來越大以便煙花向下掉
          var winWidth = document.documentElement.clientWidth || document.body.clientWidth;
          var winHeight = document.documentElement.clientHeight || document.body.clientHeight;
          if (aDiv[i].offsetLeft < 0 || aDiv[i].offsetLeft > winWidth || aDiv[i].offsetTop > winHeight) {
            document.body.removeChild(aDiv[i]);
            aDiv[i] = null;
          }
          count++;
        }
        if (count == 0) { //當所有的div小塊掉出螢幕是清除定時器
          clearInterval(newtimer);
        }
      }, 30)
    }
  }, 30)
} 
</script>
</body>
</html>

相關文章