簡體   English   中英

如何將mouseenter()或mouseleave()添加到同一類的多個元素?

[英]How can I add mouseenter() or mouseleave() to multiple elements of the same class?

我想創建一個簡單的游戲,您必須從一個平台移動到另一個平台,而又不會掉線。 基本上,當您將鼠標懸停在第一個平台上時,游戲就會開始,一旦到達最后一個平台,您就贏了。 如果您在任何時候懸停,就會自動失敗。

我正在開發我的第一個原型,但似乎無法使用同一類將懸停效果結合到多個元素上。 每當我離開第一個平台時,都會觸發該事件,盡管該事件與同一類的另一個元素重疊。 有辦法防止這種情況嗎?

這是我的代碼:

 $('.platform-win').mouseenter(function() { alert("You Win!"); }); $('.platform').mouseleave(function() { alert("You Lose!"); }); 
  /*Size & Positioning*/ .platform-container { width: 1400px; height: 700px; position: relative; } .platform-win { width: 90px; height: 90px; left: 1305px; top: 605px; position: absolute; z-index: 1; } #one{ width: 1400px; height: 100px; position: absolute; } #two{ width: 100px; height: 700px; position: absolute; left: 1300px; } /*Animations*/ /*Colors and Fonts*/ .platform-container { background-color: grey; } .platform-win { background-color: green; } #one{ background-color: rgba(255,0,0,0.5); } #two{ background-color: rgba(255,0,0,0.5); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="platform-container"> <div class="platform-win"></div> <div class="platform" id="one"></div> <div class="platform" id="two"></div> </div> 

使用$(el).each()遍歷它們:

$('.platform-win').each(function() {
  $(this).mouseenter(function() {
        alert("You Win!");
    });
    $(this).mouseleave(function() {
        alert("You Lose!");
    });
});

使用relatedTarget

 $('.platform').mouseleave(function(e) {
        if ($(e.relatedTarget).hasClass('platform-container')) {
            alert("You loose");
        }
 });

您可以執行類似全局計時器變量的操作。 每次鼠標離開障礙物時,都會啟動一個計時器。 每次鼠標進入一個塊時,它都會停止計時器。 如果計時器超過0.01秒或您選擇的任何值,則計為損失。 但是,如果用戶從有效框移動到有效框,則計時器不應走得那么遠。 只是一個主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM