如何通过javascript增加和减少图像宽度的时间?

时间:2015-06-07 15:59:49

标签: javascript

我使用以下javascript代码,但它没有像心跳一样正常工作: -

<script>         
     var y = document.getElementById("p2");
     var x = document.getElementById('myImg');
     setInterval(function(){
                x.height = "110";
                x.width="120"; 
                setInterval(function(){
                            x.height = "98";
                            x.width="107";
                            },3000);
                },2000);
</script>

2 个答案:

答案 0 :(得分:0)

不是很清楚你想要实现的目标,但是......如果你想从一种尺寸到另一种尺寸交替,那么下面的例子可能对你有帮助:

&#13;
&#13;
var y = document.getElementById("p2");
var x = document.getElementById('myImg');

var state = true;

var timerId; // do window.clearTimeout(timerId) to stop de alternation

function alternate(){
  x.height = state ?  110 : 98;
  x.width= state ? 120 : 107; 
  state = !state;
  timerId = window.setTimeout(alternate, 1000);
}

alternate();
&#13;
<p id="p2"></p>
<img id="myImg" src="https://placeholdit.imgix.net/~text?txtsize=19&txt=200%C3%97200&w=200&h=200" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用窦和动画循环。以您设置的间隔开始循环。只需确保动画循环在重新启动之前有时间完成。您可以使用CSS宽度和高度来代替使用此处的变换。

var img = document.querySelector("img"),
    style = img.style;                                  // use styles

setInterval(animateHeart, 1100);                        // interval to animate

function animateHeart() {

  var time = 0,                                         // time for sine function
      rate = 0.2,                                       // speed of sine function
      radius = 0.5;                                     // added to 100% of its scale
  
  (function loop() {                                    // inner loop
    var scale = 1 + Math.abs(Math.sin(time) * radius);  // calc scale
    time += rate;
    if (time >= Math.PI*2) {
      style.transform =                                 // reset scale
        style.webkitTransform = "scale(1,1)";
      return
    }

    // set CSS transform to scale smoothly (alt. use width/height)
    style.transform = 
      style.webkitTransform = "scale(" + scale + "," + scale + ")";

    requestAnimationFrame(loop);                        // loop animation
  })(); 
}
<img src="http://i.stack.imgur.com/gcAtB.png">