Jquery .hover,然后.click动画麻烦



更新:我已经合并了我的代码,并试图添加if/else语句。我还没有弄清楚如何点击忽略mouseenter/mouselleave功能

$('#storybtn').on({
mouseenter:function(){
    $('#story')
        .stop()
        .animate({top:'405px'},'slow');
},
mouseleave:function(){
    $('#story')
        .stop()
        .animate({top:'435px'},'slow');
},
click:function(){
    var position = $('#story').css('top');
    if (position>'10px'){
    $('#story')
        .stop()
        .animate({top:'10px'},'slow');
        }
    else (position='10px'){
    $('#story')
        .stop()
        .animate({top:'435px'},'slow');
        }
    }
});

我已经为您创建了一个示例小提琴:

例子小提琴

为了避免在点击发生后出现mouseleave动画,我在#story中添加了一个类click,并在mouseleave之后添加了一个if/else case来检查它是否存在,或者删除它:

 $('#storybtn').on({
        mouseenter: function () {
            $('#story')
                .stop()
                .animate({top: '405px'}, 'slow');
        },
        mouseleave: function () {
            if (!$('#story').hasClass('clicked')) {
            $('#story')
                .stop()
                .animate({top: '435px'}, 'slow');
            } else {
                $('#story').removeClass('clicked')
            }
        },
        click: function () {
            var position = $('#story').css('top');
            if (position > '10px') {
                $('#story')
                    .addClass('clicked')
                    .stop()
                    .animate({top: '10px'}, 'slow');
            } else if (position === '10px') {
                $('#story')
                    .addClass('clicked')
                    .stop()
                    .animate({top: '435px'}, 'slow');
            }
        }
    });

首先,新版本的jQuery不支持使用.hover()的语法。其次,您需要在激活新动画之前停止其他动画,否则它会将其排队,直到之前的动画完成。试试这个:

$('#storybtn').on({
    mouseenter:function(){
        $('#story')
            .stop()
            .animate({top:'405px'},'slow');
    },
    mouseleave:function(){
        $('#story')
            .stop()
            .animate({top:'435px'},'slow');
    },
    click:function(){
        $('#story')
            .stop()
            .animate({top:'10px'},'slow');
    }
});

这使用了。on()处理程序,这就是.click().hover()的简写。通过使用真实的东西,您可以整合您的代码。

最新更新