定时器的使用01

本文介绍了JavaScript中的定时器(setTimeout和setInterval)及其清除方法(clearTimeout和clearInterval),并展示了如何使用这些定时器来控制DOM元素的显示与隐藏。此外还提到了Date对象的用法以及兼容性问题解决方案,例如使用charAt()方法。

关键词:定时器、清除定时器、Date对象、charAt()

定时器:间隔性(setInterval)、延时性(setTimeout); 清除定时器:clearInterval(name),name为需要关闭的定时器的名称;对应的还有clearTimeout; Date(): 包括getHours(),getMinutes(),getSeconds(),getFullYear(),getMonth(),getDate(),getDay(),其中getMonth()获取的月份是从0开始的; charAt: 兼容低版本的获取元素的方法,比如获取str中第i位元素:str[i]=str.charAt(i);

测试题

延时提示框(如何实现)

代码演示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style lang="">
        .box{
            width: 350px;
            height: 200px;
        }
        #left{
            width: 200px;
            height: 200px;
            background-color: yellow;
            float: left;
            display: none;
        }
        #right{
            width: 100px;
            height: 100px;
            background-color: red;
            float: right;
        }
        
    </style>
</head>
<body>
    <div class="box">
        <div id="left"></div>
        <div id="right"></div>
    </div>
    <script>
        
        var oLeft = document.getElementById('left');
        var oRight = document.getElementById('right');
        var timer = null;

        // oRight.onmouseover = function(){
        //     clearTimeout(timer); // 防止鼠标离开左边 div 的时候 div 消失
        //     oLeft.style.display = 'block'
        // };
        // oRight.onmouseout = function(){
        //     timer = setTimeout(function(){
        //         oLeft.style.display = 'none'
        //     },500)
        // };
        // oLeft.onmouseover = function(){
        //     clearTimeout(timer)
        // };
        // oLeft.onmouseout = function(){
        //     timer = setTimeout(function(){
        //        oLeft.style.display = 'none'
        //     },500)
            
        //简化代码 合并 mouseover   和 mouseout
        oRight.onmouseover = oLeft.onmouseover = function () {
            clearTimeout(timer); // 防止鼠标离开左边 div 的时候 div 消失
            oLeft.style.display = 'block'
        };
        oRight.onmouseout = oLeft.onmouseout = function () {
            timer = setTimeout(function () {
                oLeft.style.display = 'none'
            }, 500)
        };
     
    </script>
</body>
</html>
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值