我想无限重复功能,但我做不到

时间:2019-06-01 15:39:58

标签: javascript function loops

我想对背景做些影响,以便我可以添加一些形状,但我只能循环1种形状,我不能循环

我多次尝试调用函数,但这没有帮助

-keep class com.google.android.gms.analytics.** { *; }
-keep class com.google.android.gms.gcm.** { *; }
-dontwarn com.google.android.gms.**

2 个答案:

答案 0 :(得分:1)

尝试以这种方式调用“动画”功能

setInterval(function(){anim()},5);

答案 1 :(得分:0)

您的问题是您要为window.onload函数分配 function animasyon

中的值

window.onload仅包含1个功能。如果您多次调用动画功能,那么最后一个将覆盖第一个。

编辑:您需要将动画逻辑与页面加载逻辑分开。它们是完全独立的东西。

这里是添加多个对象并分别设置动画效果的示例。

// HTML
<div id="container">
  <div id="ball"></div>
  <div id="ball2"></div>
  <div id="ball3"></div>
  <div id="ball4"></div>
</div>
// CSS
#ball, #ball2, #ball3, #ball4 {
  background: red;
  border: 1px solid #FAFDFA;
  display: inline-block;
  width: 1em;
  height: 1em;
  border-radius: 2em;
  position: absolute;
}

#ball2 {
  background: blue;
}

#ball3 {
  background: green;
}

#ball4 {
  background: purple;
}

#container {
  width: 512px;
  height: 512px;
  background: black;
  position: relative;
}
// JS
const container = document.getElementById('container');
const stageWidth = 512;
const stageHeight = 512;
const makeFall = (elementId) => {
    // this function makes an enlement fall in random direction
  const animationSpeed = 4;
  // your onload function
  const ball = document.getElementById(elementId);
  let directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
  let directionY = Math.random() * animationSpeed;
  const setRandomStart = () => {
    ball.style.top = '10px';
    ball.style.left = (Math.random() * (stageWidth / 2)) + 'px';
    directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
    directionY = Math.random() * animationSpeed;
  }
  setRandomStart();
  let animationInterval = setInterval(() => {
    let px = parseFloat(ball.style.left);
    let py = parseFloat(ball.style.top);
    px += directionX;
    py += directionY;
    if (px > stageWidth - 20 || py > stageHeight    - 20 || px < -20) {
      setRandomStart();
    } else {
      ball.style.left = px + 'px';
      ball.style.top = py + 'px';
    }


  }, 48);
}

// In Your onload function you can add the elements and then animate


makeFall('ball');
makeFall('ball2');
makeFall('ball3');
makeFall('ball4');

https://jsfiddle.net/753oL8re/4/