【Web】Web-API(No.67)定时器实现星星闪烁

定时器实现星星闪烁

在这里插入图片描述
需要素材点击图片联系我或私信、评论

效果图

【Web】Web-API(No.67)定时器实现星星闪烁_第1张图片


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>一闪一闪亮晶晶title>
    <style>
        * {
      
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
      
            background-color: #000000;
        }

        .star {
      
            width: 15px;
            height: 15px;
            position: absolute;
            font-size: 12px;
            margin-top: 50px;
            color: lightyellow;
        }
    style>
    <script>
        //等页面所有的都加载完毕之后在执行后面的函数
        window.onload = function () {
      
            var timeId;
            var flag = true;//开关:默认是开的
            my$("btn1").onclick = function () {
      
                if(flag){
      
                    flag = false;//立马关闭开关
                    //每过100毫秒改变一次星星的位置
                    timeId = setInterval(function () {
      
                        //设置随机数


                        //设置元素的top值和left值
                        var star = document.getElementsByTagName("div");
                        for (var i = 0; i < star.length; i++){
      
                            var x = Math.ceil(Math.random() * 1300);
                            star[i].style.left = x + "px";
                        }
                        for (var j = 0; j < star.length; j++){
      
                            var y = Math.ceil(Math.random() * 550);
                            star[j].style.top = y + "px";
                        }
                    },100)
                }
            }
            my$("btn2").onclick = function () {
      
                clearInterval(timeId);
                flag = true;
            }
        }
    script>
head>
<body>
<button id="btn1">一闪一闪button>
<button id="btn2">停止button>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<div class="star">div>
<script src="common.js">script>
body>
html>

你可能感兴趣的:(Web-API,Web,API)