Bouncing ball 5 times jquery/javascript beginners level

☆樱花仙子☆ 提交于 2019-12-24 08:19:51

问题


I am quite new to js and jQuery and wanted to achieve a simple animation that has been discussed many times here: a bouncing ball. However, I did not find the answer to my specific question as topics discussed already were much more sophisticated.

I want a quite simple animation: five bounces and stay on the ground with the sixth. That one I have achieved so far. But for the five bounces I want to decrease the distance of bounce by 20% of the initial distance. Say the distance is 100, it should bounce to 80 first then to 60... to 20 to 0.

You can see my attempts here.

Or just the js code here:

$(function() {

    var time = 500;
    var bounces = 5;

    function bounceDown(){
      $(".ball").animate({top: 200}, time, function(){
        bounceUp();
      });
    };

    function bounceUp() {
      $(".ball").animate({top: 100}, time);
    };

    function shadowUp(){
      $(".shadow").animate({width: 100, height: 10, left: 85, top: 245, opacity: 1}, time,    
    function(){
        shadowDown();
      });
    };

    function shadowDown() {
      $(".shadow").animate({width: 0, height: 0, left: 130, top: 225, opacity: 0}, time);
    };     

    function finalDown(){
        $(".ball").animate({top: 200}, time);
    };

    function finalShadow(){
        $(".shadow").animate({width: 100, height: 10, left: 85, top: 245, opacity: 1}, time);    
    };

    $(".button").on("click", function(){
      for (var i = 0; i < bounces; i++){
        setTimeout(function(){
          bounceDown();
          shadowUp();      
        }, time*2*i);
        setTimeout(function(){
          finalDown();
          finalShadow();
      }, 5000);
      };               
    });
});

回答1:


You can declare your initial top_bounce value:

var top_bounce = 100;

And then change your bounceUp function to:

function bounceUp() {
  $(".ball").animate({top: top_bounce}, time);
    top_bounce = top_bounce + 20;
};

Like you can see here: http://jsfiddle.net/darkajax/5wASf/

And about the "bonus question" mentioned in your comment, it'd be something similar, declare a variable like: var shadow_size = 0; and then your function like:

function shadowDown() {
        console.log(shadow_size);
      $(".shadow").animate({width: shadow_size*100, height: shadow_size*10, left: 110, top: 225, opacity:  0}, time);
        shadow_size += 0.2;

    };

You can see the fiddle updated, also you'd just have to do something similar with left to make it look centered



来源:https://stackoverflow.com/questions/15205466/bouncing-ball-5-times-jquery-javascript-beginners-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!