我有一个带有div
的网页,里面有几张图片。 div
有“幻灯片”的id。我正在尝试制作幻灯片功能,但采用更“定制”的方式来选择div
。但是,这不起作用,问题是什么?我将“旧”代码放在较新的代码下面,有两行需要修改才能看到想要的结果。链接: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);
它不起作用,因为你只是传入一个字符串(“幻灯片”),并且在任何时候都不会将任何元素作为其id
属性。
您可以扩展slideShow
函数以检查container
参数是否为字符串,如果是,请抓取相关元素:
var slideShow = function(container, time) {
if (typeof container === "string")
container = document.getElementById(container);
...
};
您可能还应该在继续执行之前检查您的container
变量是否包含HTMLElement
:
if (!(container instanceof HTMLElement))
return false;
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);