代码之家  ›  专栏  ›  技术社区  ›  Arash

如何使用Color box jQuery插件来处理direct<img>元素?

  •  1
  • Arash  · 技术社区  · 9 年前

    colorbox .
    我尝试在其上使用colorbox的HTML结构如下:

    <div class="image-gallary">
      <img src="/patch_to_image/image_1.png">
      <img src="/patch_to_image/image_2.png">
      <img src="/patch_to_image/image_3.png">
      <img src="/patch_to_image/image_4.png">
    </div>
    

      $('div.image-gallary>img').colorbox({
        rel:'images',
        transition:"fade",
        opacity:0.5 ,
        rel:'group1'
      });
    

    当我点击图像时,会显示clorbox load和popup,但不会加载图像(不显示,仍在加载图像)。

    screenshot

    1 回复  |  直到 9 年前
        1
  •  2
  •   Terry    9 年前

    这是因为颜色盒取决于 href 属性,以便正确加载页面。简单的解决方法是简单地将每个包装起来 <img src="/path/to/image"> 具有相应 <a href="/path/to/image"> ,你可以走了。

    这些图像是用来点击的,因此直观地说,它们应该被包装在一个可交互的元素中 ( <a>

    $(function() {
      $('div.image-gallary>a').colorbox({
        rel: 'images',
        transition: "fade",
        opacity: 0.5,
        rel: 'group1'
      });
    });
    img {
      width: 100px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js"></script>
    
    <div class="image-gallary">
      <a href="http://i.imgur.com/YzuqChn.gif"><img src="http://i.imgur.com/YzuqChn.gif"></a>
      <a href="http://i.imgur.com/Am3foce.gif"><img src="http://i.imgur.com/Am3foce.gif"></a>
    </div>

    如果您不想修改标记,有一种替代解决方案:您可以简单地使用 href .colorbox() 方法,因为您将需要指向其 src

    $(function() {
      $('div.image-gallary>img').each(function() {
        // Iterate through individual images...
        // because we need access to their 'src' attribute
        $(this).colorbox({
          rel: 'images',
          transition: "fade",
          opacity: 0.5,
          rel: 'group1',
          href: $(this).attr('src')
        });
      });
    });
    img公司{
    宽度:100px;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js"></script>
    
    <div class="image-gallary">
      <img src="http://i.imgur.com/YzuqChn.gif" />
      <img src="http://i.imgur.com/Am3foce.gif" />
    </div>