0

通常のマウス脱退機能は完全に機能していますが、マウスを非常にゆっくりと離すと、マウスアウト機能が機能しません。

var timeoutId;
$('.box').mouseover(function(){
        var $this=$(this);
        if (!timeoutId) {
            timeoutId = window.setTimeout(function() {
            timeoutId = null;
                $this.animate({
                    marginTop:'-224px',
                    height:'300px'
                    })
    $this.find('.rotate-arrow').addClass('rotate');
    $this.find('.header-content-span').css('display','none');
                                                   },1000); }
            });
$('.box').mouseleave(function(){
        var $this=$(this);
         if (timeoutId) {
            window.clearTimeout(timeoutId);
            timeoutId = null;
            $this.animate({
                marginTop:'0px',
                height:'77px'
                })
    $this.find('.rotate-arrow').removeClass('rotate');
    $this.find('.header-content-span').css('display','block');

        }
4

1 に答える 1

2

コードの設定方法では、コンテナに1秒以上mouseleaveホバーした場合、アニメーションは発生しません。.box

これは、がトリガーtimeoutIdされるとすぐにクリアされ、コールバックには、が定義されている場合にのみアニメーションを実行するロジックが含まれているためです。setTimeoutmouseleavetimeoutId

これを解決するには、ifステートメントからアニメーションを引き出します。簡単な例を次に示します。

var timeoutId;
$('.box').mouseenter(function () {
    var $this = $(this);
    if (!timeoutId) {
        timeoutId = window.setTimeout(function () {
            timeoutId = null;
            $this.stop().animate({
                height: '100px'
            });
        }, 1000);
    }
});
$('.box').mouseleave(function () {
    var $this = $(this);
    if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
    }
    $this.stop().animate({
        height: '50px'
    });
});

注:mouseenterこれは。とは逆のイベントタイプであるため、使用しましたmouseleave。特定の状況に応じて、これら2つのハンドラーは、バインドされたオブジェクトの子孫のイベントバブリングを処理する方法のために、mouseover使用するよりも適切な選択になる傾向があります。mouseout

jsfiddle

于 2013-02-21T08:25:35.183 に答える