我正在尝试将此脚本作为外部javascript文件运行,任何人都可以帮我一把吗?还需要将其放在我的网页中的div标签中
var imgArray = new Array("Home Page/Images/Slideshow/bus-resize.jpg",
"Home Page/Images/Slideshow/.jpg",
"Home Page/Images/Slideshow/.jpg");
var imgCount = 0;
function startTime() {
if(imgCount == imgArray.length) {
imgCount = 0;
}
document.getElementById("img2").src = imgArray[imgCount];
imgCount++;
setTimeout("startTime()", 5000);
}
答案 0 :(得分:0)
为了使您的代码能够正常工作,您需要的是HTML中的这一行:
<imd id=img2></img><script>startTime();</script>
但请不要使用此解决方案,因为它会通过更改src属性来重复请求,即使对于已加载的图像也是如此。
而是使用它来做同样的事情,但不是改变src属性,而是使用3个元素并隐藏其中的2个元素。
的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;
}