【问题标题】:function opens popup not before second click功能不会在第二次点击之前打开弹出窗口
【发布时间】:2014-12-03 02:06:12
【问题描述】:

我在 laravel 环境中使用 magnific popup 并希望两者一起工作,所以我写了这个:

Here's a fiddle with the problem

$(document).ready(function() {

    $('.image-popup-vertical-fit').on('click',function(){
    var image = $(this).attr('src');

    popnow(image);
});

    function popnow(a) {

    $('.image-popup-vertical-fit').magnificPopup({

        type: 'image',
        closeOnContentClick: true,
        mainClass: 'mfp-img-mobile',
        image: {
            verticalFit: true
        },
        items: {
        src: a
            }

    });
}
    });

HTML:

<div class="col-lg-6 col-sm-6 margin-top-60">
    {{HTML::image('images/recentprojects1.png','recent',array('class' => 'img-responsive img-center image-popup-vertical-fit')) }}
</div>

<div class="col-lg-6 col-sm-6 margin-top-60" id="test">
    {{ HTML::image('images/pricing1.png','recent',array('class' => 'img-responsive img-center image-popup-vertical-fit')) }}
</div>

如果我在页面重新加载后第一次单击弹出式打开图像,则没有任何反应,如果我第二次单击它会打开。

但是当我在页面重新加载后第一次点击第一个 div 之后我点击第二个时,它仍然向我显示第一个点击的 div 的内容(第一次点击第二个 div - 错误的图像)。

所以似乎每次点击都不需要var image。我的功能有问题吗?

当我将console.log(a) 添加到function popnow(a) 的顶部时,会记录正确的图像src。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    只需对每张图片进行迭代并为每张图片添加魔法。然后,您只需单击每个图像即可打开弹出窗口。

    Working fiddle

    function popnow(){
      $('.image-popup-vertical-fit').each(function(){
        var image = $(this).attr('src');
        $(this).magnificPopup({
    
            type: 'image',
            closeOnContentClick: true,
            mainClass: 'mfp-img-mobile',
            image: {
                verticalFit: true
            },
            items: {
                src: image
            }
          });
       });
    }
     // Init function
      popnow();
    

    PS:我使用了来自 CDN 的插件。使用 jsfiddle 时,请尝试从 CDN 加载插件或库,而不是从工作区加载。

    【讨论】:

      【解决方案2】:

      magnificPopup 所做的是启用弹出窗口。因此,首先单击您只是启用它,而不是调用它。 第二次点击第二张图片会弹出第一张,是因为你启用它时将src设置为第一张图片。

      $(document).ready(function() {
          $('.image-popup-vertical-fit').each(function(i, el) {
              $(el).magnificPopup({
                      type: 'image',
                      closeOnContentClick: true,
                      mainClass: 'mfp-img-mobile',
                      image: {
                        verticalFit: true
                      },
                      items: {src: $(el).attr('src')}
              });
          });
      });
      

      Fiddle

      顺便说一句,我把代码放在了 magnificPopup 插件之后。最好在代码使用之前加载插件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多