javascript - 放大弹出窗口 : open by clicking on something other than the image

标签 javascript jquery magnific-popup

客户要求图像标题在悬停时完全覆盖缩略图,因此我现在需要能够单击标题来打开放大弹出窗口,而不是 <a> 。到目前为止我已经能够做到:

JS/jQuery:

jQuery(".caption").on("click", function(event) {
  var items = [];
  jQuery(".item").each(function() {
    items.push( {
      src: jQuery(this).find("a").first().attr("href")
    } );
  });
  jQuery.magnificPopup.open({
    type: 'image',
    gallery: {
      enabled: true
    },
    items: items,
    image: {
      titleSrc: function(item) {
        console.log( item.el );
        // return item.el.clone();
      }
    }
  });
});

参见fiddle 为例,以及 HTML 和 CSS(加上也不起作用的替代 JS)。

它给了我两个阻碍:

  1. 弹出的始终是第一个图像,而不是用户点击的图像。
  2. 关于 return item.el.clone(); 的部分被注释掉,因为它产生“item.el is undefined”错误(当通过 jQuery('.caption').magnificPopup() 而不是 jQuery.magnificPopup.open() 实例化 magnificPopup 时,似乎不会发生这种情况)。不过,我还需要 HTML 标题显示在弹出窗口中。

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

当您使用项目数组时,您可以传递要显示的第一个项目的索引。因此,我使用 var index = jQuery(this).parent().index() 来获取当前单击项目的索引,然后将该变量传递给 magnificPopup > 功能。

为了在弹出窗口中获取标题,我向 items 对象添加了一个名为 titleSrc 的额外属性,然后您可以使用 titleSrc 选项中检索该属性item.data.titleSrc.

https://jsfiddle.net/sjp7j1zx/4/

jQuery(".caption a").on("click", function(event) {
  event.stopPropagation();
});

jQuery(".caption").on("click", function(event) {
  var items = [];
  jQuery(".item").each(function() {
    // Pass an extra titleSrc property to the item object so we can use it in the magnificPopup function
    items.push( {
      src: jQuery(this).find("a").first().attr("href"),
      titleSrc: jQuery(this).find('.caption').html()
    } );
  });

  // Get the index of the current selected item
  var index = jQuery(this).parent().index();

  jQuery.magnificPopup.open({
    type: 'image',
    gallery: {
      enabled: true
    },
    items: items,
    image: {
      titleSrc: function(item) {
       // get the titleSrc from the data property of the item object that we defined in the .each loop
       return item.data.titleSrc;
      }
    }
    // Pass the current items index here to define which item in the array to show first
  }, index);
});

关于javascript - 放大弹出窗口 : open by clicking on something other than the image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46287990/

相关文章:

javascript - 使用javascript获取内存使用信息

javascript - 来自 php 的 Ajax 响应不会将收到的数据显示为可折叠 - jquery mobile?

javascript - 如何更改 Facebook/twitter/youtube/Google+ Likes 按钮的图标

javascript - 搜索输入字段中的所有单词,然后替换 div 标签中的所有匹配单词

jQuery 照片标签显示不正确

javascript - exportTableToCSV 的 JS 变量替换怎么做?

javascript - 在Processing 3.0中使用缓动鼠标进行绘图

jquery - 为图像添加灯箱

javascript - 单击弹出窗口外部时,放大模式会关闭

php - Laravel 4 Ajax 检查以包含 XMLHttpRequest(来自 Magnific Popup)