动态气泡

102 阅读1分钟

在正文的第一句加入“我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

大家可以看下动态图

2022-09-24 123231.gif

气泡是从地下随机出现,然后向上移动,用的动画,每4s或者2s就新生成一个圆

先新建一个气泡其实就是一个div,需要用css画一个圆 这是box-shadow大家可以去看一下

        section span {
            position: absolute; // 
            bottom: -50px; //新建气泡 需要在屏幕底下,
            background: transparent; // 透明的
            border-radius: 50%;
            pointer-events: none;
            box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5); // 设置阴影 
            animation: animate 4s linear infinite; //这是向上的动画
        }

然后气泡有内部有一个点,这个颜色可以自定义的,这个我们用的伪类方式,写css来描述这个点 radial-gradient 这是径向渐变radial-gradient 这是径向渐变的解释,大家可以看一下

        section span::before {
            content: '';
            position: absolute; // 绝对定位
            width: 100%;
            height: 100%;
            transform: scale(0.25) translate(-70%, -70%);// 移动位置
            background: radial-gradient(red, transparent); // 颜色
            border-radius: 50%;
        }

下面就是需要我们写动画了,延y轴向上动画,然后顶之后opacity为0

   @keyframes animate {
            0% {
                transform: translateY(0%);
                opacity: 1;
            }

            99% {
                opacity: 1;
            }

            100% {
                transform: translateY(-1200%);
                opacity: 0;
            }
        }

后面就是js逻辑了,我们需要新建一span元素,然后随机位置生成一个,然后追加到body上,在4s之后删除节点,

 function createBubble() {
            const section = document.querySelector('section')
            const createElement = document.createElement('span')

            let size = Math.random() * 60
            createElement.style.width = 60 + size + 'px'
            createElement.style.height = 60 + size + 'px'
            createElement.style.left = Math.random() * innerWidth + 'px'
            section.append(createElement)
            setTimeout(() => {
                createElement.remove()
            }, 4000)
        }
        setInterval(createBubble, 50)

这是代码块