[英]Toggling setInterval animation on/off
New to js and learning a lot but in all my research I can't get this quite right. js的新手,学到了很多东西,但是在我的所有研究中,我都做不到。
Goal: 目标:
1: I have image1 1:我有image1
2: when clicked on runs a setinterval function between image2 and image3, animating it. 2:单击时,在image2和image3之间运行setinterval函数并对其设置动画。
3: when clicked on again clearinterval and goes to a static image1. 3:再次单击clearinterval并转到静态图像1。
bonus: no audio when static, plays audio when animate. 好处:静态时无音频,动画时播放音频。
I get caught on the thirdstep. 我陷入了第三步。
onclick function onclick功能
function clickio()
{
element=document.getElementById('myimage')
if (element.src.match("image2.png","image3.png"))
{
clearInterval("animate()");
element.src="image1.png";
audiofile.pause();
}
else
{
audiofile.play();
setInterval("animate()", 500)
}
}
Animate function 动画功能
function startfire()
{
element=document.getElementById('myimage')
if (element.src.match("flame1.png"))
{
element.src="flame2.png";
}
else
{
element.src="flame1.png";
}
}
Example at: Audibreeze 例子: Audibreeze
another issue is playing audio via various browsers. 另一个问题是通过各种浏览器播放音频。
I used the HTML5 <audio>
tag but had a fall to <embed>
tag that doesn't seem to work. 我使用了HTML5
<audio>
标签,但跌倒了<embed>
标签,但似乎无法正常工作。
This should solve your animation problem. 这应该可以解决您的动画问题。
var animInterval = null;
var clickio = function( event ){
var element = document.getElementById( 'myimage' );
if( interval ){
clearInterval( animInterval );
element.src = "image1.png";
audiofile.pause();
}
else{
audiofile.play();
animInterval = setInterval( startfire , 500 );
}
}
But I have a few suggestions you might wanna take into account. 但我有一些建议您可能需要考虑。
When creating animations it's usually better to use window.requestAnimationFrame
if you use HTML5 or a function that mimics that (like this:) 创建动画时,通常最好使用
window.requestAnimationFrame
如果您使用HTML5或模仿它的函数(例如:)
window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();
Consider preloading the images before you animate them, or even put all images in the same file (sprite) and changing a background position. 在制作动画之前,请考虑预加载图像,甚至将所有图像放入同一文件(精灵)中并更改背景位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.