我有这段代码:
var run_anim = "";
var anim_array = ["\animations\pic_1.gif",
"\animations\pic_2.gif",
"\animations\pic_3.gif",
"\animations\pic_4.gif"]
function changeBackgroundURL(elementId, backgroundURL){
run_anim = "false";
document.getElementById(elementId).style.background=backgroundURL;
}
function mouseover_anim(elementName){
run_anim = "true";
changeBackgroundURL(elementName,anim_array[0]);
while(run_anim=="true"){
setTimeout(function(){changeBackgroundURL(elementName,anim_array[1]) parameter = null},30);
setTimeout(function(){changeBackgroundURL(elementName,anim_array[2]) parameter = null},40);
setTimeout(function(){changeBackgroundURL(elementName,anim_array[3]) parameter = null},20);
}
}
我正在运行此行:
<area shape="rect" coords="0,0,95,91"
onMouseOver="mouseover_anim('div_1')"
onMouseOut="changeBackground('div_1', 'pic_static.gif')">
当我运行它时,应用程序使用了很多CPU,我需要关闭浏览器。看起来像while循环(总是如此)会阻塞孔系统(但我看不到任何图片的变化)。在浏览器中调试时,我也看不到任何错误消息。我也试过预加载图片(上面没有发布的代码),但它仍然没有用。
如果我禁用while-loop 并且设置更长的超时,代码仅有效:
function mouseover_anim(elementName){
changeBackgroundURL(elementName,anim_array[0]);
setTimeout(function(){changeBackgroundURL(elementName,anim_array[1]) parameter = null},300);
setTimeout(function(){changeBackgroundURL(elementName,anim_array[2]) parameter = null},400);
setTimeout(function(){changeBackgroundURL(elementName,anim_array[3]) parameter = null},200);
}
因此用Javascript创建循环动画和/或快速动画是不可能的?或者你有什么建议吗?
答案 0 :(得分:1)
@alfasin如果@Marcus希望它是一个快速动画,3秒超时太多了,所以也许大约100毫秒?第二件事 - 使用true,而不是&#34; true&#34; - 你能看到区别么? :)最后,但最重要的是 - 使用setInterval每隔n毫秒调用一次函数,你不会遇到浏览器崩溃的问题(当然你需要记住clearInterval,否则它会无休止地运行< / p>
由于我有空闲时间,所以这里几乎是完整的代码:
var intervalId = setInterval(function() {
// do your stuff here
// write condition, that when satisfied clears this interval
//clearInterval(intervalId);
}, 100);
答案 1 :(得分:0)
这是它适合我的方式(我更改了图像名称/路径并在FF&amp; chrome上进行了本地测试):
<html>
<head>
<style type="text/css">
div {
position: absolute;
left: 200px;
top: 200px;
width: 800px;
height: 900px;
style: "background: url(\"1.jpg\")";
}
</style>
<script type="text/javascript">
var anim_array = ["url(\"1.jpg\")",
"url(\"2.jpg\")",
"url(\"3.jpg\")",
"url(\"4.jpg\")"]
function changeBackgroundURL(backgroundURL){
document.getElementById("1").style.backgroundImage = backgroundURL;
}
function mouseover_anim(){
var bg = document.getElementById("1").style.backgroundImage;
if(bg === anim_array[0] || bg === ""){
bg = anim_array[1];
}
else if(bg === anim_array[1]){
bg = anim_array[2];
}
else if(bg === anim_array[2]){
bg = anim_array[3];
}
else if(bg === anim_array[3]){
bg = anim_array[0];
}
changeBackgroundURL(bg);
}
</script>
</head>
<body>
<div id="1"></div>
<img src ="1.jpg" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
<area shape="rect" id="1" coords="0,0,200,200" onMouseOver="setTimeout(mouseover_anim,3000);" >
</map>
</body>
</html>