鼠标移入移出元素显示与隐藏的技巧

在做网站右上角的退出登录时,需要鼠标移到头像上显示退出按钮,移出时不显示退出按钮。另外头像和退出按钮是同级元素,同在一个父元素中。如果直接用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')
        }
    )

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值