js制作星星闪特效

效果如下
在这里插入图片描述
思路呢?

  1. 准备一张星星的图片
  2. 创建多个星星(可以利用for循坏)
  3. 求出可视网页的宽高 clientWidth,clientHeight
  4. 设置星星的随机坐标 利用 Math.random()
  5. 设置星星的缩放可以用css中的scale
  6. 设置星星的缩放延迟频率 animationDelay
  7. 给星星加动画(鼠标移动时,星星方法旋转)

代码如下

 <style>
        *{
    
    
          margin: 0;
            padding: 0;
            list-style: none;
        }

        body{
    
    
            background-color: #000;
        }

        span{
    
    
            width: 30px;
            height: 30px;
            background: url("../images_js/star.png") no-repeat;
            position: absolute;
            background-size:100% 100%;
            animation: flash 1s alternate infinite;
        }

        @keyframes flash {
    
    
            0%{
    
    opacity: 0;}
            100%{
    
    opacity: 1;}
        }

        span:hover{
    
    
            transform: scale(3, 3) rotate(180deg) !important;
            transition: all 1s;
        }
    </style>
</head>
<body>
<script>
    window.onload = function () {
    
    
        // 1. 求出屏幕的尺寸
        var screenW = document.documentElement.clientWidth;
        var screenH = document.documentElement.clientHeight;

        // 2. 动态创建星星
        for(var i=0; i<150; i++){
    
    
            // 2.1 创建星星
            var span = document.createElement('span');
            document.body.appendChild(span);

            // 2.2 随机的坐标
            var x = parseInt(Math.random() * screenW);
            var y = parseInt(Math.random() * screenH);
            span.style.left = x + 'px';
            span.style.top = y + 'px';

            // 2.3 随机缩放
            var scale = Math.random() * 1.5;
            span.style.transform = 'scale('+ scale + ', ' + scale + ')';

            // 2.4 频率
            var rate = Math.random() * 1.5;
            span.style.animationDelay = rate + 's';
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/qq_41309350/article/details/114324226