2016-12-07 4 views
0

ユーザーがマウスを特定の要素の上に移動すると、クラスを非表示にして表示することができました。しかし、私が実際に気に入っているのは、ユーザーが選択したdivだけでなく、画面上の任意の場所にマウスを移動したときに表示されることです。要素自体だけでなく、マウスが画面上のどこにでも移動したときにdivを表示する方法は?

これは私の現在のコードです:

$(window).on('mousemove', function() { 
    $('.barhide').addClass('show'); 
    try { 
    clearTimeout(timer); 
    } catch (e) {} 
    timer = setTimeout(function() { 
    $('.barhide').removeClass('show'); 
    }, 1000); 
}); 

そして、私のCSS:

.barhide { 
    background: #333; 
    color: #fff; 
    display: block; 
    opacity: 0; 
    transition: all 1.5s ease; 
} 

.barhide.show { 
    opacity: 1; 
    display: none; 
} 

だから私は希望のものを3秒後、.barhideを持つクラスが隠され得るということであり、ユーザーの場合画面上でマウスを動かすと、要素の上を移動するのではなく、再び表示されます。

また、私はReactでこれらのことを行う方が簡単ではないかと思いましたか?

答えて

2

私は少しコードを再構成し、何が起こっているのかを説明するコメントを追加しました。また、タイマーをクリアしようとすると例外がスローされないので、tryを失います。

mouseoverタイプのイベントは、モバイルデバイスの問題です。これら二つの記事は、その点で役立つことがあります。

JQuery's Virtual Mouse Events

Simulated Mouse Events using JQuery

$(function(){ 
 
    // When page loads, wait 3 seconds and hide all elements with .barhide class: 
 
    setTimeout(toggle, 3000); 
 
}); 
 

 
var timer = null; 
 

 
// General function for adding/removing the "hide" class. 
 
// This is used when the page first loads and each time 
 
// the mouse moves on the page. We're not calling toggle() 
 
// here because a flicker effect can happen which would leave 
 
// the elements showing instead of being hidden. 
 
function toggle(){ 
 
    $('.barhide').toggleClass('hide'); 
 
} 
 

 
$(window).on('mousemove', function(){ 
 
    // When anywhere on page is moused over bring back .barhide 
 
    // elements for 3 seconds. Removing "hide" simply restores 
 
    // the original CSS & layout 
 
    $('.barhide').removeClass('hide'); 
 
    
 
    // Kill any previous timers 
 
    clearTimeout(timer); 
 
    
 
    // Wait 3 seconds and hide again 
 
    timer = setTimeout(toggle, 3000) 
 
});
.barhide { background-color:blue; } 
 
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="barhide">ONE</div> 
 
<div class="show">TWO</div>

+0

あなたが誤ってあなたが要素の上にマウスを動かし続けるならば、あなたはそれがすぐに原因古いタイムアウトに消え –

+0

を削除しました@ RoryMcCrossanうん、私はコードの別の部分を見ていた。まだ目覚めていない!回答が更新されました。 –

+0

を消去されていない/表示されて続けていることがわかります 'てclearTimeout()'コールすぎ –

0

あなただけの実行中のタイマーのNRをカウントしたときに最後の仕上げは、あなたがバーを非表示にします。

var count = 0; 

$(window).mousemove(function(event) { 
    $('.barhide').show(); 
    count += 1; 

    setTimeout(function() { 
    if (count == 1) { 
     $('.barhide').hide(); 
    } 
    count -= 1; 
    }, 3000); 
}); 
+0

これはうまくいきませんが、要素はもう隠れません。 – Deelux

関連する問題