【问题标题】:How to remove class by click function using jquery如何使用jquery通过点击功能删除类
【发布时间】:2014-06-18 22:15:11
【问题描述】:

我有一个图像...我想要什么:当我点击它时,它应该被放大并且应该添加一个名为“close”的类。因此,当我再次单击它时,图像应调整为其原始大小,并且我想在可以再次单击它以增长的同时删除该类... 我成功添加了一个类,但我无法删除它。

HTML:

<div class="intro-img">
    <img src="uploads/images/2.jpg" alt="Sensuality 1" />
</div>

CSS:

.intro-img {
    position: relative;
    display: block;
    height: 80%;
    max-width: 80%; 
    margin: 5% auto;
}
.intro-img img {
    height: 100%;
    max-width: 100%;
    cursor: pointer;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -ms-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
.intro-img img:hover {
    height: 105%;
    max-width: 105%;
}

脚本:

$('.intro-img img').click(function(){
    $('.intro-img img').addClass( 'close');
    $('.intro-img').animate({'height':'100%','max-width':'100%','margin': '0 auto'}, 500, 'easeInCirc');
});
$('.intro-img .close').click(function(){
    $('.intro-img').animate({'margin': '5% auto','height':'80%','max-width':'80%'}, 500, 'easeInCirc');
    $(this).removeClass('close');
});

如何通过第二次点击删除“关闭”类?我的脚本有什么问题? (我读过一篇关于它的帖子here,但我不能用它来处理我的情况)

【问题讨论】:

    标签: jquery removeclass


    【解决方案1】:

    您的脚本尝试立即将单击处理程序附加到与.intro-img .close 匹配的所有元素,但在单击图像之前文档中没有此类元素。因此,点击处理程序没有附加到任何东西。

    一个好的解决方案是改用delegated event handler,例如

    $('.intro-img').on('click', '.close', function(){
        $('.intro-img').animate(...);
        $(this).removeClass('close');
    });
    

    此处理程序附加到.intro-img(从一开始就存在)并在任何与.close 匹配的后代被点击时激活——这正是您想要的。

    更新:但是,如果您执行上述操作,那么您的第一个事件处理程序会在单击 .close 时触发。为防止这种情况发生,您可以检查处理程序中的 img 是否有 .close,或者您可以使用以下解决方案。

    另一个好的解决方案是使用单个处理程序来打开和关闭,即将两个事件处理程序替换为:

    $('.intro-img img').click(function(){
        var $this = $(this), isClose = $this.is(".close");
        if (!isClose) {
            $('.intro-img').animate(...);
        }
        else {
            $('.intro-img').animate(...);
        }
        $this.toggleClass("close");
    });
    

    【讨论】:

    • 非常感谢...现在,使用您的方法,当我单击图像时,它会变大并同时调整为原始大小,您可以在这里看到它:photography.igorlaszlo.com/test2.html#sensuality
    • @IgorLaszlo:那是因为第一个事件仍在触发。我更新了答案(同时我还添加了另一种没有这个问题的方法)。
    • #Jon Perfect,它可以正常工作!谢谢,我投票赞成接受的答案!
    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2011-01-28
    相关资源
    最近更新 更多