在里面有图像的所有锚标签上启动fancybox

时间:2012-03-18 17:14:11

标签: jquery fancybox

我在启动fancybox时遇到问题。我想在#content块内的所有图像上使用fancybox。所有图像都有以下代码:

<a href="img.jpg">
<img title="title" src="img.jpg" alt="alt" width="225" height="169">
</a>

我不想为链接使用特殊类(图片由用户通过tinymce管理)。我试过了:

$("#content a").has('img').fancybox({
..fancybox settings
});

以及

$("#content a img").parent('a').fancybox({
..fancybox settings
});
没有任何运气。 $("#content a").has('img').hide()完美无缺 - 所以选择合适的元素就好了。

编辑:也许为了更好地理解:使用$("#content a")有效,但适用于所有<a>标记,这意味着像<a href="google.com">google</a>这样的简单链接“ fancyboxed”。

EDIT2: HTML代码:

<div id="content">
<p>Lots of text.
    <a href="href">
        <img src="src" alt="alt" width="225" height="169" />
    </a>
</p>
<p>another text</p>
<p>more text <a href="http://www.google.com">Simple link which should not be opened by fancybox</a></p>
</div>

感谢任何想法。

5 个答案:

答案 0 :(得分:5)

$('a').has('img') 应该返回所有a元素,因为它不起作用真的很奇怪。怎么样:

img

答案 1 :(得分:2)

这应该启用包含id内容的div下所有图像的fancybox。

 $("#content img").fancybox({
    ..fancybox settings
    });

这应该在内容div中的所有带有图像的标签上启用fancybox。

$("#content a").each(function(){
    if($(this).has("img"))
    {
        $(this).fancybox({
             //..fancybox settings
         });
    }
  });  

答案 2 :(得分:2)

为什么不直接定位链接到图片而不是那些在其内容中包含图片的链接?这可能就是你所需要的,因为Fancybox用于显示大图像。

这很容易做到:

//build a selector that targets all links ending in an image extension
var thumbnails = 'a[href$=".gif"],a[href$=".jpg"],a[href$=".jpeg"],a[href$=".png"],a[href$=".GIF"],a[href$=".JPG"],a[href$=".JPEG"],a[href$=".PNG"]';

//add "fancybox" class to those (this step could be skipped if you want) and group them under a same "rel" to enable previous/next buttons once in Fancybox
jQuery(thumbnails).addClass("fancybox").attr("rel","lightbox");

//call fancybox
jQuery('.fancybox').fancybox();

答案 3 :(得分:0)

好吧,我终于开始工作了。由于jQuery .has() Target Different Element,我刚刚将长度属性添加到您的代码中。

$(document).ready(function() {
   $('#content a').each(function () {
    if ($(this).has('img').length) {
        $(this).fancybox();
    }
});

我不得不说,我不知道为什么$('#content a').has('img').hide();不起作用。当我尽可能地“清理”代码时,它起作用了。我无法找到导致问题的元素。

答案 4 :(得分:-1)

<a rel="example_group" href="img.jpg">
<img title="title" src="img.jpg" alt="alt" width="225" height="169">
</a>


$("a[rel=example_group]").fancybox({
..fancybox settings


});

$("#content a[rel=example_group]").fancybox({
..fancybox settings


});

尝试使用这个给一个rel来锚

相关问题