点击div外隐藏jQuery

3

你好,

我正在尝试用JavaScript实现动态显示图像。

这是我的代码:

<div class="info_image_click" style="display: none;">
    <img src="slike/info_slika_click.jpg" />
</div><!--kraj info_image_click-->

<a href="javascript:void(null);">
    <div class="info_image" style="margin: 0px auto;">
        <img src="slike/info_slika.jpg"/>
    </div>
</a><!-- info slika -->

<script>
    $('.info_image').click(function () {
        $('.info_image_click').show();
    });
</script>

当用户点击“info_image”(小图片)时,会打开“info_image_click”(大图片)。我不知道用户如何通过在容器外部单击来隐藏“info_image_click”。抱歉我的英语不好 :)

你使用的是哪个jQuery来打开图片?展示一些更多代码的链接。 - Code Lღver
5个回答

6

试试这个:

$('.info_image').click(function (e) {

    // Used to stop the event bubbling..
    e.stopPropagation()
    $('.info_image_click').show();
});

// Hide the "info_image_click" by clicking outside container
$(document).click(function () {
    $('.info_image_click').hide();
});

非常感谢,我在这个领域还是个新手。 - Pavo Gabrić
另一个问题 :) 图像位于body标签中,但我无法将其居中,以便它始终位于监视器的中心。这是我的CSS中的body行: body { background-image: url("slike/noisy_net.png"); background-repeat: repeat;} - Pavo Gabrić
尝试一下:在body标签内添加以下代码:background-image: url(slike/noisy_net.png); background-repeat:no-repeat; background-position: center center; :) - palaѕн
这是我的主要背景,但我想居中的图片在我的第一个问题中,确切地说是 <div class="info_image_click" style="display: none;"><img src="slike/info_slika_click.jpg" /></div> 这个。 - Pavo Gabrić

1
尝试使用
$(document).not('. info_image_click').click(function() {
    // Do your hiding stuff here.
});

1
添加 body 的点击事件:
<script>
 $('.info_image').click(function () {
            $('.info_image_click').show();
            $("body").click(function () {
                $("info_image_click').hide();
            });
        });
</script>

0
如果可能的话,尝试更改你的DOM,这样就不需要使用jQuery了。
<a href="your large image"><img src="your small image"></a>

0
如果您想要实现的是使图像模态化(即在隐藏图像之前页面下方不活动),您可以创建一个不可见的覆盖层(通常为0.01的非常小的不透明度),其大小与页面相同,覆盖它,并具有z-index(“垂直”位置)介于您的页面(通常为0)和“模态”区域(即此情况下的info_image_click图像)之间,后者可以是大于0的任何内容。
然后,您设置覆盖层单击事件,以便在单击覆盖层时隐藏图像和覆盖层。
通过这样做,您确保当用户单击窗口时,如果其位于图像内部,则不会发生任何事情(因为图像具有更高的z-index,它将获得未分配的单击事件),如果其位于图像外部,则覆盖层(而不是页面,因为它具有较低的z-index)将获得单击事件并执行您想要的操作(隐藏图像和覆盖层,从而返回到主页面)。
如果您希望它成为向用户提示图像是模态的线索,则可以将覆盖层的不透明度设置为高于0.01。
以下是我如何在jQuery中完成它的快速草稿:
showWindowModal: function(windowSelector) {
    $("<div></div>")
        .addClass("overlay")
        .appendTo($("#main"))
        .css({
            width: $("#main").outerWidth(),
            height: $("#main").outerheight()
        })
        .click(function() {
            $(windowSelector).remove();
            $("#main > div.overlay").remove();
        });
    $(windowSelector).addClass("modal").show();
}

CSS类:

#main > div.overlay
{
    position: absolute;
    background: white;
    z-index: 100;
    opacity: 0.5;
    filter:alpha(opacity=50); /* For IE8 and earlier */
}

.modal
{
    z-index: 1000;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接