当前位置:   article > 正文

【五十个前端实操案例】_前端项目实战案例

前端项目实战案例

五十个前端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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

逻辑代码

// 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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/979334
推荐阅读
相关标签
  

闽ICP备14008679号