定时器防抖案例

HTML:

<body>
        <div class="wrapper">
            <div class="center">

            </div>
            <div class="main">
                <div class="left">
                    <a href="#" class="sy">首页</a>
                    <a href="#" class="jcss clickColor">基础设施</a>
                    <a href="#" class="sjzy">数据资源</a>
                </div>
                <div class="right">
                    <a href="#" class="yyzc">应用支撑</a>
                    <a href="#" class="bzgf">标准规范</a>
                    <a href="#" class="aqbz">安全保障</a>
                </div>
            </div>
        </div>

    </body>

CSS:

.wrapper {
    width: 1920px;
    height: 90px;
    overflow: hidden;
    position: relative;
}
.center{
    width: 25%;
    height: 85%;
    position: absolute;
    left: 50%;
    top: 0%;
    transform: translate(-50%,0%);
    cursor: pointer;
}

.main {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    background-color: transparent;
    background: url(../img/nav.png) center no-repeat;
    background-size: contain;
    overflow: hidden;
    transition: transform 1.5s;
}
/*初始化移动出去*/
.move {
    transform: translateY(-70%);
}

JS:

    let enterTime;
    let leaveTime;
    let timer;
    $(".wrapper").hover(function() {
        enterTime = Date.now(); // 鼠标划入的时的时间
        $(".main").removeClass("move");
        // 如果鼠标刚离开又瞬间划入,并且setTimeOut还没有执行完,
        // 此时鼠标第二次移入的时间减去第一次离开的时间间隔小于2000毫秒时,
        // 清除定时器(表示刚离开又想看添加“后悔”的过程)
        if((enterTime - leaveTime) <= 2000) {
            clearTimeout(timer);
        }

    }, function() {
        leaveTime = Date.now(); // 鼠标离开的时间
        timer = setTimeout(function() {
            $(".main").addClass("move");
        }, 2000);
    });

 

原文地址:https://www.cnblogs.com/xiejn/p/11963244.html