【五十个前端实操案例】

五十个前端JavaScript实操案例(二)

手风琴轮播图

线上地址: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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值