我的网页中包含div
和一些图片。 div
的ID为"幻灯片"。我正在尝试制作幻灯片功能,但是有更多"自定义"选择div
的方式。但是,这不起作用,问题是什么?我把'#34; old"在较新的代码下面,有两行需要修改才能看到想要的结果。链接:https://en.khanacademy.org/computer-programming/js-library-exatreojs-slideshow-library/2950604004
var slideShow = function(container, time) {
this.images = [];
this.curImage = 0;
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.display = "none";
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
this.images[i].style.display = "none";
}
this.images[this.curImage].style.display = "block";
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlide.bind(document.getElementById(this), time);
// old code (works): window.setTimeout(nextSlide.bind(this, time);
};
nextSlide.call(this);
};
slideShow("slideshow", 1000);
// old code (works): slideShow(document.getElementById("slideshow"), 1000);
答案 0 :(得分:1)
它不起作用,因为你只是传入一个字符串(&#34;幻灯片&#34;)并且在任何时候都不会将任何元素作为其id
属性。
您可以扩展slideShow
函数以检查container
参数是否为字符串,如果是,请抓取相关元素:
var slideShow = function(container, time) {
if (typeof container === "string")
container = document.getElementById(container);
...
};
在继续执行之前,您可能还应检查container
变量是否包含HTMLElement
:
if (!(container instanceof HTMLElement))
return false;
答案 1 :(得分:0)
var slideShow = function(container, time) {
var containerEl = document.getElementById(container);
this.images = [];
this.curImage = 0;
for (i = 0; i < containerEl.childElementCount; i++) {
this.images.push(containerEl.children[i]);
this.images[i].style.display = "none";
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
this.images[i].style.display = "none";
}
this.images[this.curImage].style.display = "block";
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlide.bind(document.getElementById(this), time);
// old code (works): window.setTimeout(nextSlide.bind(this, time);
};
nextSlide.call(this);
};
slideShow("slideshow", 1000);