day36-Hoverboard(悬浮滑板)

50 天学习 50 个项目 - HTMLCSS and JavaScript

day36-Hoverboard(悬浮滑板)

效果

在这里插入图片描述

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hoverboard</title>
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <!-- 容器 -->
    <div class="container" id="container"></div>
    <script src="script.js"></script>
</body>

</html>

style.css

* {
    box-sizing: border-box;
}

body {
    background-color: #111;
    /* 子元素居中 */
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    overflow: hidden;
    margin: 0;
}

/* 容器 */
.container {
    /* 子元素居中 */
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    max-width: 400px;
}

/* 方块 */
.square {
    background-color: #1d1d1d;
    box-shadow: 0 0 2px #000;
    height: 16px;
    width: 16px;
    margin: 2px;
    /* 5s 是过渡的持续时间 也是此时方块的显示颜色时间 */
    transition: all 5s ease;
}

/* 悬浮方块时 */
.square:hover {
    /* 过渡时间为0 */
    transition-duration: 0s;
}

script.js

// 重点 flex  transition
// 1.获取元素节点
const container = document.getElementById('container')//容器
const colors = ['#e74c3c', '#8e44ad', '#3498db', '#e67e22', '#2ecc71']//颜色
const SQUARES = 500 //方块数量
// 2.遍历绑定事件
for (let i = 0; i < SQUARES; i++) {
    // 创建方块
    const square = document.createElement('div')
    // 添加方块样式
    square.classList.add('square')
    // 鼠标经过 设置颜色
    square.addEventListener('mouseover', () => setColor(square))
    // 鼠标移出 去除颜色
    square.addEventListener('mouseout', () => removeColor(square))
    // 将方块添加置容器中
    container.appendChild(square)
}
// 函数:设置元素颜色
function setColor(element) {
    const color = getRandomColor()
    element.style.background = color
    element.style.boxShadow = `0 0 2px ${color}, 0 0 10px ${color}`
}
// 函数:将元素的颜色恢复为默认效果
function removeColor(element) {
    element.style.background = '#1d1d1d'
    element.style.boxShadow = '0 0 2px #000'
}
// 函数:随机获取颜色值
function getRandomColor() {
    return colors[Math.floor(Math.random() * colors.length)]
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值