如何在悬停时检测上一个元素

时间:2018-06-05 06:53:56

标签: javascript jquery html

您能否请一看这个演示,让我知道当鼠标悬停在id上时如何检测前一个元素的#box-5

例如,我想控制日志记录鼠标移入#box-5

的每个div的id

$("#box-5").hover(function(){
   console.log("Entering From ...")
    }, function(){
    
});
body {
  padding: 20px;
}
#box{
  width:320px;
  height:300px;
}
.map{
  height:100px;
  width:100px;
  border:1px solid #ccc;
  float:left;
}
#box-5{
  background:khaki;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div id="box-1" class="map"></div>
<div id="box-2" class="map"></div>
<div id="box-3" class="map"></div>
<div id="box-4" class="map"></div>
<div id="box-5" class="map"></div>
<div id="box-6" class="map"></div>
<div id="box-7" class="map"></div>
<div id="box-8" class="map"></div>
<div id="box-9" class="map"></div>
</div>

2 个答案:

答案 0 :(得分:3)

跟踪变量中的最后一个悬停元素,并在每次悬停其中一个元素时更新它

$("#box-5").hover(function(){
   console.log("Entering From ..." + last_box)
    }, function(){
    
});

var last_box = null;
$('.map').hover(function(){
   if($(this).attr('id') != 'box-5'){
       last_box = $(this).attr('id');
   }
})
body {
  padding: 20px;
}
#box{
  width:320px;
  height:300px;
}
.map{
  height:100px;
  width:100px;
  border:1px solid #ccc;
  float:left;
}
#box-5{
  background:khaki;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div id="box-1" class="map"></div>
<div id="box-2" class="map"></div>
<div id="box-3" class="map"></div>
<div id="box-4" class="map"></div>
<div id="box-5" class="map"></div>
<div id="box-6" class="map"></div>
<div id="box-7" class="map"></div>
<div id="box-8" class="map"></div>
<div id="box-9" class="map"></div>
</div>

答案 1 :(得分:0)

您可以将悬停元素的id存储在单独的变量中,并且每次在悬停事件处理函数中更改它。

let hoveredId = 0;

$(".map").hover(function() {
    this.id !== 'box-5' ? hoveredId = this.id 
                        : console.log(`Entering from ${hoveredId}`);
}, () => {});
body {
  padding: 20px;
}

#box {
  width: 320px;
  height: 300px;
}

.map {
  height: 100px;
  width: 100px;
  border: 1px solid #ccc;
  float: left;
}

#box-5 {
  background: khaki;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div id="box-1" class="map"></div>
<div id="box-2" class="map"></div>
<div id="box-3" class="map"></div>
<div id="box-4" class="map"></div>
<div id="box-5" class="map"></div>
<div id="box-6" class="map"></div>
<div id="box-7" class="map"></div>
<div id="box-8" class="map"></div>
<div id="box-9" class="map"></div>
</div>