javascript - 如何将 mouseenter() 或 mouseleave() 添加到同一类的多个元素?

标签 javascript jquery html css

我想创建一个简单的游戏,您必须在其中从一个平台穿越到另一个平台,而不能从边缘掉下来。基本上,当你将鼠标悬停在第一个平台上时,游戏就开始了,一旦你到达最后一个平台,你就赢了。如果你在任何时候徘徊,你就自动输了。

我正在开发我的第一个原型(prototype),我似乎无法使用同一个类为多个元素组合悬停效果。每当我离开第一个平台时,尽管与同一类的另一个元素重叠,事件仍会触发。有没有办法防止这种情况?

这是我的代码:

$('.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>

最佳答案

使用relatedTarget:

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

关于javascript - 如何将 mouseenter() 或 mouseleave() 添加到同一类的多个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47417368/

相关文章:

javascript - 使用 Javascript 以指数方式旋转 PNG

javascript - 在 Angular JS 工厂中返回变量?

javascript - 使用 Break 循环 for with 无限循环? ReactJs

javascript - 无法使用 Express 和 Mongoose 存储新用户

jquery UI 日期选择器 : calculate minDate x years from today

Java Web 应用程序合理的表单步骤

javascript - jQuery :empty not working with input

javascript - 隐藏/显示某些 UL 元素?

javascript - 使用 javascript 处理跨浏览器功能

html - :hover table rows don't revert to their pre-:hover state 的属性