带有querySelectorAll的lightgallery.js

问题描述

我试图在多个类中使用querySelectorAll运行lightgallery.js脚本(纯JS版本)。

这是我正在使用的代码

var lg = document.querySelectorAll( '.gallery-1,.gallery-2,.gallery-3');
for ( var i = 0; i < lg.length; i++ ) {
    lightgallery( lg[i],{
        selector: '.gallery-item > a:has(img)',mode: 'lg-fade',preload: 2,counter: false,download: false
    });
}

我在控制台中收到“ lightgallery未正确启动”错误。之前,我使用的是lightgallery脚本的jQuery版本,而使用$( '.gallery-1,.gallery-3' ).lightgallery()则没有问题。

解决方法

罪魁祸首是脚本中:has()选项中使用的selector:has()是jQuery扩展,不是CSS规范的一部分,因此不能在纯JS脚本中使用。

更新:

这是我现在正在使用的代码:

var lg = document.querySelectorAll( '.gallery-1,.gallery-2,.gallery-3');
for ( var i = 0; i < lg.length; i++ ) {
    lightGallery( lg[i],{
        selector: '.gallery-item > a[href$=".jpg"],.gallery-item > a[href$=".jpeg"],.gallery-item > a[href$=".png"],.gallery-item > a[href$=".gif"]',mode: 'lg-fade',preload: 2,counter: false,download: false
    });
}