简体   繁体   English

为什么 setinterval animation 不起作用?

[英]Why is setinterval animation not working?

I have tried to create the animation of a cat walking using setInterval and a function that changes style property left.我尝试使用 setInterval 和一个改变样式属性的 function 创建猫的 animation。 This does however not work.然而,这不起作用。 There is no animation.没有 animation。 And I have done everything correctly so I don't know why It's not working.而且我已经正确完成了所有操作,所以我不知道为什么它不起作用。

<html>
    <head>
        <meta charset="utf-8">
        <title>Challenge: Catwalk</title>
        <style>
            #cat {
                position: absolute;
                left: 0px;
            }
        </style>
    </head>
    <body>
    <div>
        <!-- Cat walking GIF from: http://www.anniemation.com/clip_art/graphics.html -->
        <img id="cat" src="https://www.kasandbox.org/programming-images/misc/cat-walk.gif">
    </div>

  <script>
  var catEl = document.getElementById("cat");

  function walkTheCat(){
      catEl.style.left=parseFloat(catEl.style.left)+40+"px"
  };
  setInterval(walkTheCat,1000)
  </script>

    </body>
</html>```


The simplest solution is to use a counter.最简单的解决方案是使用计数器。 left = left + 40 and that will ensure the cat animates across the screen. left = left + 40这将确保猫在屏幕上动画。

var left = 0;
function walkTheCat() {
  catEl.style.left = left;
  left = left + 40;
};

setInterval(walkTheCat, 1000)

I've recorded a screencast showing you how I solved this.我录制了一个截屏视频,向您展示了我是如何解决这个问题的。 You can find a highlight of the solution here .您可以在此处找到解决方案的亮点


catEl.style.left does not provide the css property. catEl.style.left不提供 css 属性。 See me try to log it here .看我尝试在这里记录它

You can loop the cat by detecting when the image breaks window.innerWidth .您可以通过检测图像何时中断window.innerWidth来循环猫。 See my looping cat here . 在这里看到我的循环猫

Styles set by CSS does not appear in the element's style property.由 CSS 设置的 Styles 不会出现在元素的样式属性中。 To make it work either change it to use inline style for left or use getComputedStyle .要使其正常工作,请将其更改为对left使用内联样式或使用getComputedStyle I personally think using inline style is simpler:我个人认为使用内联样式更简单:

<html>
    <head>
        <meta charset="utf-8">
        <title>Challenge: Catwalk</title>
    </head>
    <body>
    <div>
        <!-- Cat walking GIF from: http://www.anniemation.com/clip_art/graphics.html -->
        <img id="cat" style="left:0px" src="https://www.kasandbox.org/programming-images/misc/cat-walk.gif">
    </div>

....

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

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