您能否请一看这个演示,让我知道当鼠标悬停在id
上时如何检测前一个元素的#box-5
?
例如,我想控制日志记录鼠标移入#box-5
$("#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>
答案 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>