赞
踩
线上地址:https://github.com/bradtraversy/50projects50days
案例演示
业务功能
1、鼠标经过小盒子区域,会随鼠标移动随机添加背景色
2、鼠标离开小盒子区域,背景颜色变成过渡回原来的颜色
git项目地址逻辑代码 - 分析代码
实现思路
1、创建小盒子节点,追加小盒子到页面上
2、创建颜色数组,随机抽取颜色,渲染到小盒子上
3、鼠标经过,小盒子添加背景颜色,离开,移除背景颜色
案例知识点
1、节点操作:创建追加节点
2、Math对象:随机数
基本结构和样式
<style> body { /* 快速实现垂直水平居中 */ display: flex; align-items: center; justify-content: center; overflow: hidden; margin: 0; height: 100vh; background-color: pink; } .container { display: flex; align-items: center; justify-content: center; background-color: black; /* 拆行或拆列 div之间有空行 */ flex-wrap: wrap; width: 400px; height: 500px; } .square { background-color: #6b6b6b; /* 盒子阴影 */ box-shadow: 0 0 2px #252525; height: 16px; width: 16px; margin: 2px; /* 动画效果 ease 曲线进行过渡,持续2秒: */ transition: 2s ease; } .square:hover { /* 定义过渡效果花费的时间 */ transition-duration: 0s; } @media (max-width: 480px) { .container { /* width: 100vh; height: 100vh; */ flex: 0.7; } .square { height: 12px; width: 12px; } } </style>
逻辑代码
// 1 获取元素 const container = document.querySelector('.container'); // 色块数组 const colors = ['#F3698a','#F1b8c7','#D1foea','#67d5b5','#Bfe4fb','#6da8fc','#366bd5',]; // 节点数量 const square = 500; for (let i = 0; i < square; i++) { const square = document.createElement('div'); // 添加类 square.classList.add('square'); // 给追加的小盒子绑定鼠标经过事件 square.addEventListener('mouseover', function () { // 获取随机数 let randomColor = Math.floor(Math.random() * colors.length); this.style.background = colors[randomColor]; square.style.boxShadow - `0 0 2px ${randomColor}, 0 0 10px ${randomColor}`; // console.log(randomColor); }); // 鼠标离开 square.addEventListener('mouseout', function () { this.style.background = '#6b6b6b'; square.style.boxShadow - '0 0 2px #fff'; }); // 追加节点 container.appendChild(square); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。