简体   繁体   中英

JavaScript animation position issue

I have a basketball and a basketball button. When I click the button, the basketball bounces up and down. I've managed to style the basketball and button to my desired location on the screen.

But when I click on the "Animate Basketball" button the ball does bounce up and down, but it relocates itself to the top of my page and then starts bouncing up and down. Can someone please look at my code and tell how I can stop the ball from relocating when I click the button?

<head>
   <script src="script.js"></script>
</head>
<input id="ballButton" onclick="checkButton()" type="button" value="Animate Basketball"
<div id="basketball" style="position:absolute;top:430px;left:700px;">
   <img src="http://img.netlumination.com/Basketball_64x64-1.png" Basketball" \>
</div>

CSS:

#ballButton {
  position:absolute;
  top:400px;
  left:700px
}

JS:

var distanceBall = 0;
var directionBall = 1;
var timerToggle = null;
function animateBall() {
  document.getElementById("basketball").style.top = distanceBall + "px";
  distanceBall += directionBall;
  if (distanceBall > 200) { directionBall = -1; }
  if (0 > distanceBall) { directionBall = 1; }
  timerToggle = setTimeout(function () { animateBall(); }, 10);
}

function checkButton() {
  if (document.getElementById("ballButton").value == "Animate Basketball") {
    document.getElementById("ballButton").value = "Stop Basketball";
    animateBall();
  } else {
    document.getElementById("ballButton").value = "Animate Basketball";
    clearTimeout(timerToggle);
  }
}

Your variable distanceBall is the problem. When you fetch the basketball with getElementById your code says that its CSS 'top' property is 0px. Change the distanceBall variable to about 410px. here is an example: Working ball animation

here is another codebit that can help: CSS ball animation

Hope I helped!

Here's a (though quick and dirty) working solution. I think this is what you meant.

http://jsfiddle.net/9guaa0j5/1/

I added some pixels to your starting variable distanceBall and manually added 230px to one of your functions.

var distanceBall = 200;
var directionBall = 1;
var timerToggle = null;
function animateBall() {
document.getElementById("basketball").style.top = distanceBall + 230 +"px";
distanceBall += directionBall;
if (distanceBall > 200) { directionBall = -1; }
if (0 > distanceBall) { directionBall = 1; }
timerToggle = setTimeout(function () { animateBall(); }, 10);
}

Hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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