javascript - 以编程方式打开 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 的方法。
解决方案
该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>
推荐阅读
- python - 如何停止函数在循环内重新分配布尔值
- postgresql - 相等运算符使用索引但在运算符中不使用
- sql - SQL (GBQ) 中 2 个时间段计算的百分比变化
- iccube-reporting - 仪表板桌面布局响应?
- django - 返回具有多个 id 的相同产品
- r - Spark ML_pipelines:管理表读取
- ruby-on-rails - 查找与 current_user 在同一组中的用户关联的所有记录
- mongodb - 如何在 mongodb 中像 mySQL 中的 LIKE 一样查找文本?
- javascript - 关于javascript函数结构的问题
- azure-devops - 当状态发生变化时如何在 VSTS 中触发事件