灯箱没有't在jquery 1.9.0及以后的版本中消失

lightbox doesn't disappear in jquery version 1.9.0 and after

本文关键字:消失 版本 jquery      更新时间:2023-09-26

所以我试着制作这个灯箱

css

#wrapper{
    width: 100%;}
#locandine{
    padding-top: 6%;
    width: 66.5%;
    text-align: justify;
    -ms-text-justify: distribute-all-lines;
    text-justify: distribute-all-lines;}
#locandine a{
    width: 24%;
    vertical-align: top;
    display: inline-block;
    *display: inline;}
.loc img{
    width: 100%;
    max-height: 432px;}

#lightbox {
    position:fixed;
    top:0; 
    left:0; 
    width:100%; 
    height:100%; 
    background-color: rgba(0,0,0,0.5);
    text-align:center;
}
#lightbox img{
    max-height: 90%;
}

html

<body>
<div id="wrapper" align="center">
    <div id="locandine" class="locandine">
        <h1>Locandine</h1>
        <a href="pagine/immagini/loc1.png" class="loc">
            <img src="pagine/immagini/loc1.png" alt="loc1">
        </a>
        <a href="pagine/immagini/loc2.png" class="loc">
            <img src="pagine/immagini/loc2.png" alt="loc2">
        </a>
        <a href="pagine/immagini/loc3.png" class="loc">
            <img src="pagine/immagini/loc3.png" alt="loc3">
        </a>
    </div>
</div>
</body>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>

javascript

jQuery(document).ready(function($) {
    $('.loc').click(function(e) {
        e.preventDefault();
        var image_href = $(this).attr("href");
        if ($('#lightbox').length > 0) { 
            $('#content').html('<img src="' + image_href + '" />');
            $('#lightbox').show();
        }
        else { 
            var lightbox = 
            '<div id="lightbox">' + //insert clicked link's href into img src
                '<img src="' + image_href +'" />' +
            '</div>';
            $('body').append(lightbox);
        }
    });
    //Click anywhere on the page to get rid of lightbox window
    $('#lightbox').live('click', function() { //must use live, as the lightbox element is inserted into the DOM
        $('#lightbox').hide();
    });
});

问题是,如果我使用jquery 1.9.0及更高版本(我使用的是http://code.jquery.com/jquery-|versionHere|.js)。那么我该如何解决这个问题,我必须更改部分代码还是更改jquery库?

.live()自v1.7起已被弃用,取而代之的是.on()。检查浏览器控制台中的错误消息总是一个好主意——我很确定这会引发错误:)

因此,您应该使用:

$('document').on('click', '#lightbox', function() {
    // Function to close lightbox here
});

上面的代码有效地监听了文档对象处lightbox元素的点击,甚至是冒泡:)