简体   繁体   English

如何在同一元素上使用.hover和.click

[英]How to use .hover and .click on same element

The idea is to move a div downwards slightly when hovered and when clicked to move further down to reveal content. 这个想法是在悬停时向下移动一个div,当点击进一步向下移动以显示内容时。 The problem is that when you have clicked the div and it moves down you are no longer hovering on it so it performs the 'close when not hovered function. 问题是,当你点击div并向下移动时,你不再在它上面盘旋,所以它执行'关闭时没有悬停功能。

$(function () {
    $('.more').hover(function () { //Open on hover 
        $('#pull_down_content').animate({
            'top': '-360px'
        }, 1000);
    }, function () { //Close when not hovered
        $('#pull_down_content').animate({
            'top': '-380px'
        }, 1000);
    });
});
$('.more').click(function () { //Move down when clicked
    $('#pull_down_content').animate({
        'top': '0px'
    }, 1000);
});

Put a class on the element to signify that it has been clicked, and do not close it if it has that class: 在元素上放置一个类以表示它已被单击,如果它具有该类,则不要关闭它:

$(function() {        
    $('.more').hover(function(){    //Open on hover 
           $('#pull_down_content').animate({'top':'-360px'},1000);
        },    
        function(){   //Close when not hovered
           if (!$('#pull_down_content').hasClass("expanded"))
               $('#pull_down_content').animate({'top':'-380px'},1000);    
        });
    });
    $('.more').click(function(){    //Move down when clicked
        $('#pull_down_content').addClass("expanded").animate({'top':'0px'},1000);
    });

Of course you now need another trigger to determine when exactly to undo the hover animation after the item has been clicked; 当然,您现在需要另一个触发器来确定在单击项目后何时完全撤消悬停动画; how to do that exactly depends on the effect you want to achieve. 如何做到这完全取决于你想要达到的效果。

The problem is that when you have clicked the div and it moves down you are no longer hovering on it so it performs the 'close when not hovered function. 问题是,当你点击div并向下移动时,你不再在它上面盘旋,所以它执行'关闭时没有悬停功能。

I'm not sure I get it? 我不确定我明白了吗? You do know that the element with the bound events is not the same as the one that you are animating ? 你知道带有绑定事件的元素与你动画的元素不一样吗?

Anyway, something like this maybe: 无论如何,这样的事情可能是:

$(function() {
    $('.more').on('mouseenter mouseleave click', function(e) {
        if (!$(this).data('clicked')) {
            var Top = e.type==='mouseenter' ? '-360px' : e.type==='click' ? '0px' : '-380px';
            $('#pull_down_content').stop().animate({'top': Top}, 1000);
            if (e.type==='click') $(this).data('clicked', true);
        }else{
            if (e.type==='click') {
                $(this).data('clicked', false);
                $('#pull_down_content').stop().animate({'top': '-380px'}, 1000);
            }
        }
    });
});

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM