在做网站右上角的退出登录时,需要鼠标移到头像上显示退出按钮,移出时不显示退出按钮。另外头像和退出按钮是同级元素,同在一个父元素中。如果直接用hover来做的话,当鼠标从头像移到退出按钮时,退出按钮总是不显示,因为退出按钮的父元素并不是头像元素,因此不能通过css样式实现。
只能通过js来实现了。注意:这时需要在隐藏的js中加一个定时器,延时200ms再隐藏。代码如下:
hideMore: function (tagBox) {
var $dom = $(tagBox);
// $dom.stop(true, true).hide();
this.timer = setTimeout(function () {
$dom.stop(true, true).hide();
}, 200)
}
然后再在显示的方法中清除这个定时器:
showMore: function (tagBox) {
var $dom = $(tagBox);
$dom.stop(true, true).show();
clearTimeout(this.timer);
},
完整的代码如下:
html结构:
<div class="login-bar alrLogin">
<img class="headImg" src="../../img/Group.png" />
<span class="logout">退出</span>
</div>
js:
var userHover = {
timer: null,
showMore: function (tagBox) {
var $dom = $(tagBox);
$dom.stop(true, true).show();
clearTimeout(this.timer);
},
hideMore: function (tagBox) {
var $dom = $(tagBox);
// $dom.stop(true, true).hide();
this.timer = setTimeout(function () {
$dom.stop(true, true).hide();
}, 200)
}
}
$(".headImg").mouseenter(function () {
userHover.showMore('.logout')
})
$(".headImg").mouseleave(function () {
userHover.hideMore('.logout')
})
$(".logout").hover(
function () {
userHover.showMore('.logout')
},
function () {
userHover.hideMore('.logout')
}
)