首页 > 技术文章 > js:定时弹出图片(获取属性、setInterval函数)

zhai1997 2020-01-21 11:48 原文

1、js代码:

function init(){
    time = setInterval("showAd()",3000);
}
//书写显示广告图片的函数
function showAd(){
    //获取广告图片的位置
    var adEle = document.getElementById("img");
    //修改广告图片元素里面的属性让其显示
    adEle.style.display = "block";
    //清除显示图片的定时操作
    clearInterval(time);
    //设置隐藏图片的定时操作
    time = setInterval("hiddenAd()",3000);
}

//书写隐藏广告图片的函数
function hiddenAd(){
    //获取广告图片并设置其style属性的display值为none
    document.getElementById("img").style.display= "none";
    //清除隐藏广告图片的定时操作
        clearInterval(time);
}

2、主页面代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>定时弹出图片</title>
        <script type="text/javascript" src="js/js.js" ></script>
    </head>
    <body onload="init()">
        <div id="father">
            <img src="../img/1.jpg" width="100%" style="display: none" id="img"/>
        </div>
    </body>
</html>

3、效果展示:

(1)刚开始没有图片,显示为空白:

 

(2)三秒后图片出现:

(3)又过了三秒,图片消失:

推荐阅读