使用 javascript 禁用灯箱

Disable lightbox with javascript

我有一张图片,点击后会在灯箱中打开(来自 http://lokeshdhakar.com/projects/lightbox2/ 的脚本),我想做的是在按钮关闭时禁止它发生。 (所以点击图片没有任何作用。)

我尝试使用 .off 和 .unbind 按照网站上的其他一些答案来禁用灯箱,但 none 它们对我有用。 我也按照建议遵循 How do I dynamically enable/disable links with jQuery?,但没有运气。

下面是HTML.

<div style="margin-left:10%;padding:1px 16px;">
  <section id="four_columns">
    <article class="img-item">
      <figure>
        <a href="img/livingroom.jpg" data-lightbox="livingroom"><img id="img_window1" src="img/livingroom.jpg" width="200" height="120"></a>
        <figcaption>
          <strong>Living Room 
            <div class="onoffswitch">
              <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="window1" value="window1" checked>
                <label class="onoffswitch-label" for="window1">
                  <span class="onoffswitch-inner"></span>
                  <span class="onoffswitch-switch"></span>
                </label>
            </div>
          </strong>
        </figcaption>
      </figure>
    </article>
...

和javascript

<script type="text/javascript">
  $(document).ready(function() {
  var full_opacity = 1;
  var faded_opacity = 0.3;
  var fade_speed = 'fast';              
  var objid;

  $('input[name="onoffswitch"]').each(function() {
    objid = "#img_" + $(this).val();

    if($(this).prop('checked')) {
        $(objid).css('opacity', full_opacity);
    }
    else {
        $(objid).css('opacity', faded_opacity);
    }
});

$('input[name="onoffswitch"]').change(function() {
    var objid = "#img_" + $(this).val();
    console.log($(this).prop('checked'));
    if($(this).prop('checked')) {
        $(objid).fadeTo(fade_speed, full_opacity);
        }
        else {
            $(objid).fadeTo(fade_speed, faded_opacity);
            $(objid).parent().unbind('click'); /* Here is where I want to implement the code. */
        }
    });
});
</script>

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

您需要禁用灯箱(通过删除它查找的 data-lightbox 属性)和底层超链接的默认功能。

$lightboxes = $(".myImageLinks");    

// save the old data attributes in an array, then remove them
var lightboxData = $lightboxes.map(function() {
    return $(this).data("lightbox");
}).get();
$(objid).parent().removeAttr("data-lightbox");

// prevent the browser from traveling to the link target
var preventer = function(e) { 
    e.preventDefault();
});
$(objid).parent().click(preventer);

然后使用以下方法重新启用默认点击功能:

$(objid).parent().unbind('click', preventer);
$lightboxes.attr("data-lightbox", function(i, old) {
    return lightboxData[i];
});

禁用灯箱的另一种选择是仅删除 "data-lightbox" 属性并将其临时保存为 "data-oldlightbox" 属性。

我觉得图书馆应该使用 class 来识别哪些元素符合灯箱条件。这对用户很重要,而不仅仅是图书馆,应该在语义上进行标记。数据属性不适用于 CSS 钩子。