JS 基础 01

  • 1.使用JS简单实现图片轮拨

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .lunbo_container{
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
    </style>
    <script>
        <!--onload事件-->
        window.onload =  init();
        //设置间隔的函数
        function init(){
            setInterval("changePic()", 3000);
        }
        //更换图片的函数
        var i = 0;
        function changePic(){
            i++;
            document.getElementById("pic").src="images/" + i + ".jpeg";
            console.log(i);
            if(i==3){
                i=0;
            }

        }
    </script>
</head>
<body>

    <div class="lunbo_container">
            <h1>首页轮拨</h1>
        <img id="pic" src="images/1.jpeg" />
        <button onclick="changePic()">点击更换</button>
    </div>

</body>
</html>
  • 2. 使用JS完成页面定时弹出广告


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .lunbo_container{
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        .ad_container{
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
    </style>
    <script>
        <!--onload事件-->
        window.onload =  init();
        //设置间隔的函数
        function init(){
            setInterval("changePic()", 3000);
            //设置全局变量- setInterval的handler
            adTime = setInterval("showAd()", 3000);
        }






        //更换图片的函数
        var i = 0;
        function changePic(){
            i++;
            document.getElementById("pic").src="images/" + i + ".jpeg";
            // console.log(i);
            if(i==3){
                i=0;
            }

        }
        //显示广告的函数
        function showAd(){
            var ad = document.getElementById("ad-pic");
            ad.hidden = false;
            clearInterval(adTime);

            adTime = setInterval("hiddenAd()", 3000);
        }
        //关闭广告的函数
        function hiddenAd(){
            var ad = document.getElementById("ad-pic");
            ad.hidden = true;
            clearInterval(adTime);
        }
    </script>
</head>
<body>
    <div class="ad_container">
        <img id="ad-pic" src="images/ads/1.jpeg" hidden="true"/>

    </div>
    <div class="lunbo_container">
            <h1>首页轮拨</h1>
        <img id="pic" src="images/1.jpeg" />
        <button onclick="changePic()">点击更换</button>
        <button onclick="showAd()">显示广告</button>
    </div>

</body>
</html>


猜你喜欢

转载自blog.csdn.net/alexzt/article/details/80478283