animation in native javascript

前端 未结 3 1968
無奈伤痛
無奈伤痛 2021-01-07 06:32

How do i run an animation(like changing CSS properties) in native javascript without using jQuery library\'s animate method?? I have tried jQuery library animate and the fra

相关标签:
3条回答
  • 2021-01-07 06:51

    Here is an example:

    http://jsfiddle.net/4M3ts/1/

    function animate(object, property, start_value, end_value, time) {
      var frame_rate = 0.06; // 60 FPS
      var frame = 0;
      var delta = (end_value - start_value) / time / frame_rate;
      var handle = setInterval(function() {
        frame++;
        var value = start_value + delta * frame;
        object.style[property] = value + "px";
        if (value == end_value) {
          clearInterval(handle);
        }
      }, 1 / frame_rate);
    }
    
    animate(document.getElementById("a"), "top", 0, 100, 1000);
    
    0 讨论(0)
  • 2021-01-07 06:56

    CSS3 can automatically animate changes to most style properties, using transition. It will probably run smoother than you can get with any javascript-based animation.

    There's a nice tutorial on how to use it, here.

    0 讨论(0)
  • 2021-01-07 07:13

    Here is a short demonstration:

    function fade(element, started) {
        if (element.style.opacity > 0){
            console.log(element.style.opacity);
            element.style.opacity -= 0.02;
            setTimeout((function(e){return function(){fade(e);}})(element),10);
        }
    }
    fade(document.getElementById("myname"));
    

    Here is a jsfiddle: http://jsfiddle.net/s6Kzh/1/

    0 讨论(0)
提交回复
热议问题