为了使您的代码正常工作,您只需要 HTML 中的这一行:
<imd id=img2></img><script>startTime();</script>
但请不要使用此解决方案,因为它会通过更改 src 属性来重复请求,即使对于已经加载的图像也是如此。
而是使用它来做同样的事情,但不是更改 src 属性,而是使用 3 个元素并隐藏其中的 2 个。
http://jsfiddle.net/edFPA/3/
JS
var Each = function(array, callback){
for(var i = 0; i < array.length; ++i){
callback.apply(array, [array[i], i, array]);
}
};
var hideAll = function(elements) {
Each(elements, function(img){
img.className = 'hide';
});
};
var flipImages = document.querySelectorAll('.images-flip img');
hideAll(flipImages);
var Counter = function(init, cb, t){
this.start = function(){
init.call(this);
this.loop();
};
this.callback = cb;
this.loop = function(){
clearTimeout(this.timeout);
this.timeout = setTimeout(this.loop.bind(this), t);
this.callback.call(this);
};
this.stop = function(){
clearTimeout(this.timeout);
};
return this;
};
var flipArray = document.querySelectorAll('.images-flip');
Each(flipArray, function(flip){
flip.counter = new Counter(function(){
this.count = 0;
},
/*loop*/ function(){
hideAll(flip.children);
flip.children[this.count].className = '';
this.count = (this.count+1) % flip.children.length;
},
flip.dataset.time);
flip.counter.start();
});
html
<div class="images-flip" data-time="1000">
<img src="https://developers.google.com/apps-script/images/script-128.png">
<img src="https://developers.google.com/google-apps/images/manage.png">
<img src="https://developers.google.com/google-apps/images/apidownload128.gif">
</div>
<div class="images-flip" data-time="1500">
<img src="https://developers.google.com/_static/images/gplus-32.png">
<img src="https://developers.google.com/_static/images/android-32.png">
<img src="https://developers.google.com/_static/images/chrome-32.png">
CSS
.images-flip {
position: relative;
width: 128px; height: 128px;
float: left;
}
.images-flip img {
position: absolute;
}
.images-flip img.hide {
opacity: 0;
}