对你们来说很简单:)不确定为什么,但我的img并没有像他们想象的那样改变。 Chrome给了我错误:启动(匿名函数)。我已经多次检查了我的代码,无法弄清楚什么是错的,请帮忙。
var pictures = new Array(6);
var curPic = 0;
var begin;
pictures[0] = 'puppy0.gif';
pictures[1] = 'puppy1.gif';
pictures[2] = 'puppy2.gif';
pictures[3] = 'puppy3.gif';
pictures[4] = 'puppy4.gif';
pictures[5] = 'puppy5.gif';
function starting(){
if(curPic = 5)
curPic = 0;
else
++curPic;
document.getElementsByTagName('img')[0].src = pictures[curPic].src;
document.getElementsByTagName('img')[0].src = pictures[curPic];
}
function anima(){
if(begin)
clearInterval(begin);
begin = setInterval("starting()", 90);
}
<body>
<img src="puppy1.gif" id="pics">
<input type="button" value="start" onclick="anima();">
<input type="button" value="stop" onclick="clearInterval(begin);">
图片与index.html文件位于同一文件夹中。
答案 0 :(得分:2)
试试这个
setInterval(starting, 90);
而不是
setInterval("starting()", 90);
修改你的js
var pictures = new Array(6);
var curPic = 0;
var begin;
pictures[0] = 'puppy0.gif';
pictures[1] = 'puppy1.gif';
pictures[2] = 'puppy2.gif';
pictures[3] = 'puppy3.gif';
pictures[4] = 'puppy4.gif';
pictures[5] = 'puppy5.gif';
function starting(){
if(curPic = 5)
curPic = 0;
else
++curPic;
document.getElementsByTagName('img')[0].src = pictures[curPic];
}
function anima(){
begin = setInterval(starting, 90);
}
现在尝试
答案 1 :(得分:2)
删除此内容 - pictures[curPic].src
function starting(){
if(curPic = 5)
curPic = 0;
else
++curPic;
document.getElementsByTagName('img')[0].src = pictures[curPic];
document.getElementsByTagName('img')[0].src = pictures[curPic];
}
答案 2 :(得分:1)
当您定义setInterval
要调用的函数时,您的错误就在这里。试试这个:
setInterval(starting, 90);
来源:https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval
此外,这不存在。删除.src
(甚至更好,删除整行,无论如何重复):
pictures[curPic].src
答案 3 :(得分:1)
<head>
<style>
body {
padding: 5px;
border-left: 2px dotted brown;
text-align: center;
}
img,input,div {
margin: 0;
}
img {
box-shadow: 0px 0px 10px rgba(20,20,20,0.5);
}
</style>
</head>
<body>
<img src="http://placehold.it/350x200" id="pic"/>
<hr/>
<input type="button" value="Start" onclick="init();"/>
<input type="button" value="Stop" onclick="abort();"/>
<script>
var l = 6;
var pictures = new Array(l);
var c = 0;
var img = document.querySelector('#pic');
for(var i=0;i<l;i++) {
pictures[i] = 'http://placehold.it/350x' + parseInt(Math.random() * 100);
}
console.log(pictures);
img.src= pictures[c];
function animate() {
img.src= pictures[c];
if(c == l-1) {c = -1;}
c += 1;
}
function init() {
window.timer = setInterval(animate,1000);
}
function abort() {
if(window.timer) {clearInterval(timer);}
}
</script>
</body>