首页 > 解决方案 > 以编程方式打开 lightgallery.js

问题描述

所以我使用https://sachinchoolur.github.io/lightgallery.js/作为我的画廊,这很棒。

当用户单击并打开图像时,一切都很好。

<div id="lightgallery">
  <a href="img/img1.jpg">
      <img src="img/thumb1.jpg" />
  </a>
  <a href="img/img2.jpg">
      <img src="img/thumb2.jpg" />
  </a>
  ...
</div>

<script type="text/javascript">
    lightGallery(document.getElementById('lightgallery')); 
</script>

但是,我有一个边缘情况,我希望用户能够按下页面上的另一个图像来打开画廊。

让我们假装这是一个标签

<a id="magic_start" href="">

我以为我可以做到这一点:

$("#magic_start").click(function(e) {
  e.preventDefault();
  $("#lightgallery li:first-child a").trigger();
});

我也尝试过 click() 和 trigger('click') 但它们不起作用。

我认为因为 lightgallery.js 是它自己的人,可以这么说。

但它什么也没做。没有错误,但什么也不做。

有什么建议么?

编辑:

我目前的解决方法是...

window.location.href = window.location.href + "#lg=1&slide=0";
location.reload();

但是由于必须重新加载页面,这需要 UX 的方法。

标签: javascriptjquerylightgallery

解决方案


trigger函数需要在img元素上调用,而不是在外部a元素上。

lightGallery(document.getElementById('lightgallery'));

$("#magic_start").on("click", () => {
    $("#lightgallery a:first-child > img").trigger("click");
});
<!-- lightgallery and jQuery vendor CSS/JS -->
<link rel="stylesheet" href="https://cdn.rawgit.com/sachinchoolur/lightgallery.js/master/dist/css/lightgallery.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/sachinchoolur/lightgallery.js/master/dist/js/lightgallery.js"></script>

<a id="magic_start" href="#">CLICK TO OPEN</a>

<div id="lightgallery">
    <a href="https://via.placeholder.com/350">
        <img src="https://via.placeholder.com/150" />
    </a>
    <a href="https://via.placeholder.com/350">
        <img src="https://via.placeholder.com/150" />
    </a>
</div>


推荐阅读