如何更改div悬停时的全局变量值。
当我在课程.mehover
或.mehoverAnother
上悬停时,该课程隐藏'将添加到.mehide
或.mehideAnother
。在 hoverOut 上删除课程.mehide
或.mehideAnother
,但延迟将课程删除2秒,如果我每次将鼠标悬停在.mehover
或{{1}上将 timetolive 变量值更改为0.
请参阅下面的代码:
的Javascript
.mehoverAnother
HTML
var timetolive = 2000;
$(document).ready(function() {
$('.meHover').hover(function() {
//code here to change the timetolive var value
//the .mehide or .mehideAnother should hide immediately by changing the timetolive var value to 0
$('.mehide').addClass('hideplease');
}, function() {
setTimeout(function(){ $('.mehide').removeClass('hideplease'); }, timetolive); //delay removal of class
});
$('.meHoverAnother').hover(function() {
//code here to change the timetolive var value
//the .mehide or .mehideAnother should hide immediately by changing the timetolive var value to 0
$('.mehideAnother').addClass('hideplease');
}, function() {
setTimeout(function(){ $('.mehideAnother').removeClass('hideplease'); }, timetolive); //delay removal of class
});
});
jsfiddle示例https://jsfiddle.net/pqn01e5h/9/
答案 0 :(得分:1)
请尝试以下代码。
var timetolive = 2000;
$(document).ready(function() {
$('.meHover').hover(function() {
timetolive = 0;
$('.mehide').addClass('hideplease');
}, function() {
timetolive = 2000;
setTimeout(function(){ $('.mehide').removeClass('hideplease'); }, timetolive); //delay removal of class
});
$('.meHoverAnother').hover(function() {
timetolive = 0;
$('.mehideAnother').addClass('hideplease');
}, function() {
timetolive = 2000;
setTimeout(function(){ $('.mehideAnother').removeClass('hideplease'); }, timetolive); //delay removal of class
});
});
.container {
width: 100%;
height: 100%;
color: white;
}
.meHover {
width: 120px;
height: 40px;
background: red;
margin: 20px 0 0 0;
position: absolute;
}
.meHoverAnother {
width: 120px;
height: 40px;
background: blue;
margin: 20px 0 0 120px;
position: absolute;
}
.mehide {
width: 120px;
height: 40px;
background: yellow;
position: absolute;
margin: 60px 0 0 0;
}
.mehideAnother {
width: 120px;
height: 40px;
background: orange;
position: absolute;
position: absolute;
margin: 60px 0 0 120px;
}
.hideplease {
display: none;
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="meHover">hoverme</div>
<div class="meHoverAnother">other hoverme</div>
<div class="mehide"></div>
<div class="mehideAnother"></div>
</div>