【发布时间】:2015-07-24 19:46:50
【问题描述】:
我已经在 JavaScript 中构建了一个灯箱功能,现在我正在努力使实现在同一页面上有多个画廊时正常工作,这是我在开发时没有考虑到的功能。
为了达到预期的效果,我广泛使用数据集和 data-*-attributes(data-index 来索引,data-total 来存储 .gallery 和 data-current 中有多少张图片来存储哪个@应该显示在#lightbox 中的987654330@。带有缩略图<img>s 的.gallery 被包裹在<figure><a> 中,带有href 属性到更大的#lightbox img。
这些属性在理论上有效,并通过随附的代码返回正确的值。页面加载后,当单击其中一个画廊时,画廊按预期工作,与其他画廊隔离,循环浏览画廊图像。
关闭灯箱并单击其他画廊之一时出现问题。 在 IE 11 中,我在开发人员工具的最后 document.querySelector 行中收到 Unable to get value of... 错误。但是,当将返回的值输出到 console.log() 时,我不明白为什么它不添加用于显示第一次点击的.gallery):
这是 JS 代码的一个大大缩短的版本。变量和选择器也被翻译成英文,以便这里的人们可以更好地理解它。仔细查看 galleryindex、galleryindexarray、thisgallery、thisgallerya 和 current 变量,这是解决问题的功能所在。
var lightbox = document.createElement('div'),
gallerya = document.querySelectorAll(".gallery a"),
current, img, i, galleryindexarr = [];
for (i = 0; i < gallerya.length; i++) {
gallerya[i].addEventListener("click", function(e) {
e.preventDefault();
var galleryindex = this.parentNode.parentNode.dataset.index,
thisgallery = document.querySelector(".gallery[data-index='" + galleryindex + "']"),
thisgallerya = document.querySelectorAll(".gallery[data-index='" + galleryindex + "'] a");
if(!document.getElementById("lightbox")) {
lightbox.id = "lightbox";
document.body.insertBefore(lightbox, document.body.firstChild);
}
if(galleryindexarr.indexOf(galleryindex) == -1) {
galleryindexarr.push(galleryindex);
for (i = 0; i < thisgallerya.length; i++) {
img = document.createElement("img");
img.src = thisgallerya[i].href;
img.dataset.index = galleryindex;
lightbox.appendChild(img);
}
}
current = [].indexOf.call(thisgallery.childNodes, this.parentNode);
document.querySelector("#lightbox img[data-index='" + galleryindex + "']:nth-of-type(" + current + ")").classList.add("current");
});
}
这是test demo site with further visual clarification。如果您知道任何可以提供帮助的信息,请帮助我解决这个相当小的错误。
【问题讨论】:
-
正如您在图片中看到的,in the full code 可能在您自己的控制台中on the demo site,它们已经被记录了。至于 jQuery,我知道它更容易编写,但我放弃了它,以获得更快、更纯粹的代码。
-
对不起,我在手机上 - 我看到你确实记录了它。我什至读过挪威语:)
-
是的,是挪威语,你怎么知道的? :) 如果你有任何知识,你能帮我吗?
-
我是丹麦人,我很乐意提供帮助,但我无法在此处访问控制台或 IE11
-
我明白了,非常感谢。您什么时候可以使用;几个小时后,也许?这不是那么紧急的;我会等,只要你以后能帮助我。
标签: javascript css-selectors gallery image-gallery photo-gallery