I have tried to create the animation of a cat walking using setInterval and a function that changes style property left. This does however not work. There is no 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.
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. See me try to log it here .
You can loop the cat by detecting when the image breaks window.innerWidth
. See my looping cat here .
Styles set by CSS does not appear in the element's style property. To make it work either change it to use inline style for left
or use 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>
....
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.