简体   繁体   English

如何让球左右移动?

[英]How To Get Ball Moving Left and Right?

I have the ball moving diagonal.我让球沿对角线移动。 I need to get it moving left and right at a speed of 2 pixels per update.我需要让它以每次更新 2 个像素的速度左右移动。 After it reaches 800 pixels to the right I need to get it to move left.在它向右移动 800 像素后,我需要让它向左移动。

Css code css代码

<style>
#animationArea {
  width: 400px;
  height: 300px;
  overflow: hidden;
  border: 1px solid #000;
  position: relative;
}

.pbox {
  width: 20px;
  height: 20px;
  position: absolute;
  background-color: #FF0000;
  border-radius: 25px;
}

  </style>

JsCode代码

var dvAnimationArea = document.querySelector("#animationArea");

//create the 'ball' for this animation
var ball = document.createElement('div');
ball.classList.add('pbox');
dvAnimationArea.appendChild(ball);

//position for our 'ball'
var x = 0;
var y = 0;

//start the animation interval
setInterval(update, 30);
function update() {
  ball.style.top = y + "px";
  ball.style.left = x + "px";

  x++;
  y++;
}

I left out the JS entirelly.我完全忽略了 JS。 This animates the ball 2px at a time.这一次为球设置动画 2px。 I can do this in vanilla js on click if you like, make it pause on hover etc. Just let me know what the goal is and how long the animation should take.如果你愿意,我可以在 vanilla js 中点击,让它在悬停时暂停等等。让我知道目标是什么以及动画需要多长时间。

.pbox {
width: 20px;
height: 20px;
position: absolute;
background-color: #FF0000;
border-radius: 25px;
animation:hello 5s infinite steps(400, end);}

http://codepen.io/damianocel/pen/bVOgaZ http://codepen.io/damianocel/pen/bVOgaZ

And let me know you want the container to really be 400px wide, that is no typo?让我知道你希望容器真的是 400px 宽,这不是错字吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM