ES6实现图片切换特效

效果图

demo.html

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

head>
    meta charset="UTF-8"title>Document</bodyscript type="text/javascript">
        let arr = ["前端,jqueryjavascripthtmlcss];
        
        //补充代码
        let lis'';
        let ul  document.createElement('ul);
        function appendHTML( ...innerhtml){
            innerhtml.forEach(el => {
                let templates  `<li`+el/li>`;
                lis+=templates;
              });
           return lis;
        }
        appendHTML(...arr);
        ul.innerHTMLlis;
        document.body.appendChild(ul);
        
    scripthtml>

style.css

* {
  margin: 0;
  padding: 0;
}

body {
  background: #fafafa; url('../images/bg.png')
}

::-webkit-scrollbar {
  display: none;
}

#wrap {
  width: 1065px;
  padding-top: 50px; 0 auto; 30px; rgb(255,255);
  border-radius: 2px;
  margin-top: 100px;
}

/* 整体容器 */
.__Img__container {
  font-size: 10px;
}

 分类容器 
.__Img__container .__Img__classify {
   text-align: center; */
}

 分类按钮 
.__Img__container .__Img__classify .__Img__classify__type-btn { inline-block; .2em 1em; 1.6em;
  margin-right: 10px;
  cursor: pointer;
  border: 1px solid #e95a44;
  outline: none;
  color: #e95a44;
  transition: all .4s;
  user-select: 2px;
}

 激活状态的分类按钮 
.__Img__container .__Img__classify .__Img__classify__type-btn.__Img__type-btn-active { #e95a44;
   border: 1px solid #9b59b6; */ #fff;
}

 所有图片容器 
.__Img__container .__Img__img-container {
  position: relative; 1005px; flex;
  flex-wrap: wrap; all .6s cubic-bezier(0.77,0.175,1);
}

 单个图片容器 
.__Img__container .__Img__img-container figure { 240px;
  height: 140px; absolute;
  transform: scale(0,0);
  opacity:
  overflow: hidden; none;
}

 伪元素遮罩层 
.__Img__container .__Img__img-container figure::before { block; 100%;
  top:
  left:
  z-index: 4; rgba(58,12,5,0.5);
  content: ' '; all .3s; pointer;
}

 图片 
.__Img__container .__Img__img-container figure img { all .3s;
}

 图片标题 
.__Img__container .__Img__img-container figure figcaption { 50%; 7; 1.5em; translate(-50%,-50%);
  text-align: center; 悬停图片的时候标题显示 
.__Img__container .__Img__img-container figure:hover figcaption { 1;
}

.__Img__container .__Img__img-container figure:hover img { scale(1.1,1.1);
}

 悬停图片的时候遮罩显示 
.__Img__container .__Img__img-container figure:hover::before {

.__Img__overlay { fixed;
  right:
  bottom:
  background-color: rgba(0,.8);
  justify-content:
  align-items:

.__Img__overlay .__Img__overlay-prev-btn,.__Img__overlay .__Img__overlay-next-btn { 2px solid white;
  line-height: white; 2rem; pointer;
}

.__Img__overlay .__Img__overlay-prev-btn { 20px;
}

.__Img__overlay .__Img__overlay-next-btn {

.__Img__overlay .__Img__overlay-prev-btn:active,.__Img__overlay .__Img__overlay-next-btn:active { rgb(241,241,.4);
}

.__Img__overlay .__Img__overlay-next-btn::after { "N";
}

.__Img__overlay .__Img__overlay-prev-btn::after { "P";
}

.__Img__overlay img { scale(2,2);
}

index.js

// 1. 对图片进行分类
// 2. 生成dom元素 3. 绑定事件 4. 显示到页面上

 以插件形式完成
(function (window,document) {
  let canChange = true;
  let curPreviewImgIndex = 0;

   公共方法集合
    const methods = {
       以数组形式添加子元素
      appendChild(parent,...children) {
        children.forEach(el => {
          parent.appendChild(el);
        });
      }, 选择器
      $(selector,root = document) {
        return root.querySelector(selector);
      },1)"> 选择多个元素
      $$(selector,1)"> root.querySelectorAll(selector);
      }
    };

   构造函数
    let Img = (options) {
       初始化
        this._init(options);
       生成DOM元素
        ._createElement();
       绑定事件
        ._bind();
       显示到页面上
        ._show();
    }

   初始化
    Img.prototype._init = ({ data,initType,parasitifer }) {
      this.types = ['全部'];   所有的分类
      this.all = [];  所有图片元素
      this.classified = {'全部': []};  按照类型分类后的图片
      this.curType = initType;  当前显示的图片分类
      this.parasitifer = methods.$(parasitifer);  挂载点

      this.imgContainer = null;  所有图片的容器
      this.wrap =  整体容器
      this.typeBtnEls =  所有分类按钮组成的数组
      this.figures =  所有当前显示的图片组成的数组
       对图片进行分类
      ._classify(data);

      console.log(this.classified);//分类的结果
    };

   对图片进行分类
    Img.prototype._classify = (data) {
      let srcs = [];
       解构赋值,获取每张图片的四个信息
      data.forEach(({ title,type,alt,src }) => {
         如果分类中没有当前图片的分类,则在全部分类的数组中新增该分类
        if (!.types.includes(type)) {
          .types.push(type);
        }
         判断按照类型分类后的图片中有没有当前类型
        if (!Object.keys(.classified).includes(type)) {
          this.classified[type] = [];
        }
         判断当前图片是否已生成
        srcs.includes(src)) {
           如果图片没有生成过,则生成图片,并添加到对应的分类中
          srcs.push(src);

          let figure = document.createElement('figure');
          let img = document.createElement('img');
          let figcaption = document.createElement('figcaption');

          img.src = src;
          img.setAttribute('alt' title;
           在figure中添加img和figcaption
          methods.appendChild(figure,img,figcaption);
           将生成的figure添加到all数组中
          .all.push(figure);
           新增的这个图片会在all数组中的最后一个元素
          this.classified[type].push(this.all.length - 1);

        } else {
           去all中 找到对应的图片
           添加到 对应的分类中
          this.classified[type].push(srcs.findIndex(s1 => s1 === src));
        }

      });

    };

   根据分类获取图片
    Img.prototype._getImgsByType = (type) {
       如果分类是全部,就返回所有图片
       否则,通过map进行遍历,根据分类来获取图片数组
      return type === '全部' ? [...this.all] : this.classified[type].map(index => .all[index]);
    };

   生成DOM
    Img.prototype._createElement = () {
       创建分类按钮
      let typesBtn = 遍历分类数组
      for (let type of .types.values()) {
        typesBtn.push(`
          <li class="__Img__classify__type-btn${ type === this.curType ? ' __Img__type-btn-active' : '' }">${ type }</li>
        `);
      }

      console.log(typesBtn);//查看所有分类按钮
      
       整体的模版
        let tamplate = `
          <ul class="__Img__classify">
            ${ typesBtn.join('') }
          </ul>
          <div class="__Img__img-container"></div>
        `;

        let wrap = document.createElement('div');
        wrap.className = '__Img__container';

        wrap.innerHTML = tamplate;生成整体元素
        取得所有图片的容器
        this.imgContainer = methods.$('.__Img__img-container'查看当前分类下的图片
        console.log(this._getImgsByType(.curType));
         把当前分类下的图片数组,插入到图片容器里
        methods.appendChild(this.imgContainer,....curType));

        把可能有用的数据先挂到指定位置
        this.wrap = wrap;
        this.typeBtnEls = [...methods.$$('.__Img__classify__type-btn'this.figures = [...methods.$$('figure' 遮罩层
        let overlay = document.createElement('div');
        overlay.className = '__Img__overlay';
        overlay.innerHTML = `
          <div class="__Img__overlay-prev-btn"></div>
          <div class="__Img__overlay-next-btn"></div>
          <img src="" alt="">
        `;
         把遮罩层添加到图片墙中
        methods.appendChild(.wrap,overlay);
        this.overlay = overlay;
         当前要预览的图片
        this.previewImg = methods.$('img' 移动每张图片到合适的位置
        this._calcPosition(.figures);
      };

   获取上一次显示的图片和下一次显示的图片中,相同的图片下标(映射关系)
    Img.prototype._diff = (prevImgs,nextImgs) {
      let diffArr = [];保存两次中相同的数据的下标
      遍历前一次的所有图片
      如果在下一次中存在相同的,则获取下标index2
      prevImgs.forEach((src1,index1) => {
        let index2 = nextImgs.findIndex(src2 => src1 === src2);

        if (index2 !== -1) {
           在这个映射数组中存入下标
          diffArr.push([index1,index2]);
        }
      });

       diffArr;
    };

   绑定事件
    Img.prototype._bind =  事件代理,点击事件绑定在ul上
        methods.$('.__Img__classify',this.wrap).addEventListener('click',({ target }) => {

          if (target.nodeName !== 'LI') ;

          if (!canChange) ;
          canChange = false;

          const type = target.innerText;获取按钮上的文字(图片类型)
          const els = this._getImgsByType(type);获取对应类型的图片

          let prevImgs = this.figures.map(figure => methods.$('img',figure).src);上一次显示的图片数组
          let nextImgs = els.map(figure => methods.$('img',1)">下一次显示的图片数组

          const diffArr = this._diff(prevImgs,nextImgs);获取两次相同图片的映射关系(下标)

          diffArr.forEach(([,i2]) => {
             对下一次的所有图片进行遍历
            this.figures.every((figure,index) => {
              let src = methods.$('img' 如果下一次的图片在这一次中已经出现过
              if (src === nextImgs[i2]) {
                 则从所有图片数组中剔除该图片(从Index位置,裁剪1个)
                this.figures.splice(index,1);
                return ;
              }
              ;
            });
          });
           计算图片位置
          ._calcPosition(els);

          let needAppendEls = [];
          if (diffArr.length) {
             如果存在相同图片
            let nextElsIndex = diffArr.map(([,i2]) => i2);

            els.forEach((figure,index) => {
               如果该图片没有出现过,则需要插入
              nextElsIndex.includes(index)) needAppendEls.push(figure);
            });

          }  如果不存在相同图片
            needAppendEls = els;需要插入的图片=所有图片
          }

           上一次的图片全部隐藏掉
          this.figures.forEach(el => {
            el.style.transform = 'scale(0,0) translate(0%,100%)';
            el.style.opacity = '0';
          });

           把下一次需要显示的图片添加到图片容器中
          methods.appendChild(.imgContainer,...needAppendEls);

           设置下一次显示的动画
          setTimeout(() => els表示所有图片,包括新增的,和上一次已经显示过的
            els.forEach(el => {
              el.style.transform = 'scale(1,1) translate(0,0)';
              el.style.opacity = '1';
            });
          });

           从DOM中销毁上一次出现的图片,将图片数组转为下一次要现实的图片
          setTimeout(() =>this.figures.forEach(figure =>.imgContainer.removeChild(figure);
            });

            this.figures = els;
            canChange = ;
             保证在一次切换动画没有完成之前,拒绝进行下一次切换
             避免快速切换
          },600);

           给图片按钮添加切换时的动画效果
          this.typeBtnEls.forEach(btn => (btn.className = '__Img__classify__type-btn'));
          target.className = '__Img__classify__type-btn __Img__type-btn-active';
        });

       事件代理实现点击图片的效果
        this.imgContainer.addEventListener('click',1)"> 如果点击的不是图片或者图片描述,则返回
          if (target.nodeName !== 'FIGURE' && target.nodeName !== 'FIGCAPTION')  如果点击的是图片的描述
           则把target转为其父元素图片
          if (target.nodeName === 'FIGCAPTION') {
            target = target.parentNode;
          }

          const src = methods.$('img' 拿到当前图片索引
          curPreviewImgIndex = this.figures.findIndex(figure => src === methods.$('img'this.previewImg.src = src;把当前图片的src属性赋值给预览图

          this.overlay.style.display = 'flex';设置遮罩层布局显示

          setTimeout(() =>this.overlay.style.opacity = '1';设置遮罩层显示
          });

        });

       预览时点击遮罩层,实现预览退出
        this.overlay.addEventListener('click',() =>this.overlay.style.opacity = '0';
           箭头函数可以保留最初的this指向
          setTimeout(() =>this.overlay.style.display = 'none';
          },300);
        });

       预览点击切换上一张
        methods.$('.__Img__overlay-prev-btn',1)">this.overlay).addEventListener('click',e => {

          e.stopPropagation();阻止事件冒泡
           如果是第一张,上一张就是最后一张
          curPreviewImgIndex = curPreviewImgIndex === 0 ? this.figures.length - 1 : curPreviewImgIndex - 1 获取到需要上一张显示的图片的src,赋值给预览图的src
          this.previewImg.src = methods.$('img',1)">.figures[curPreviewImgIndex]).src;
        });

       预览点击切换下一张
        methods.$('.__Img__overlay-next-btn',1)"> {

          e.stopPropagation();
           如果是最后一张,下一张就是第一张
          curPreviewImgIndex = curPreviewImgIndex === this.figures.length - 1 ? 0 : curPreviewImgIndex + 1.figures[curPreviewImgIndex]).src;
        });

    };

   显示元素
    Img.prototype._show = () {
      methods.appendChild(this.parasitifer,1)">.wrap);

      设置出现的动画效果
      setTimeout(() => {
          figure.style.transform = 'scale(1,1)">;
          figure.style.opacity = '1';
        });
      });
    };

   计算每张图片所占的位置
    Img.prototype._calcPosition = (figures) {
      let horizontalImgIndex = 0;

      figures.forEach((figure,1)"> {
        figure.style.top = parseInt(index / 4) * 140 + parseInt(index / 4) * 15 + 'px';
        figure.style.left = horizontalImgIndex * 240 + horizontalImgIndex * 15 + 'px';
        figure.style.transform = 'scale(0,0) translate(0,-100%)';
        horizontalImgIndex = (horizontalImgIndex + 1) % 4;
      });

      let len = Math.ceil(figures.length / 4);总行数
      this.imgContainer.style.height = len * 140 + (len - 1) * 15 + 'px';解决绝对定位造成的父容器高度塌陷的问题
 把生成的图片墙挂到全局
  window.$Img = Img;
})(window,document);

data.js

 图片信息文件
const data = [

  {
    type: 'JavaScript''ES6快速入门'
  },{
    type: 'JavaScript''Javascript实现二叉树算法''Canvas绘制时钟''./assets/images/3.jpg''基于websocket的火拼俄罗斯''前端框架''React知识点综合运用实例''React组件''./assets/images/5.jpg''Vue+Webpack打造todo应用''Vue.js入门基础''./assets/images/7.jpg''使用Vue2.0实现购物车和地址选配功能''React'
  }

]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


原文连接:https://www.cnblogs.com/dupd/p/5951311.htmlES6之前已经出现了js模块加载的方案,最主要的是CommonJS和AMD规范。commonjs主要应用于服务器,实现同步加载,如nodejs。AMD规范应用于浏览器,如requirejs,为异步加载。同时还有CMD规范,为同步加载方案如seaJS。ES6在语言规格的层面上,实现了模块功能,而且...
以为Es6,javascript第一次支持了module。ES6的模块化分为导出(export)与导入(import)两个模块,其中在项目中,我们会经常看到一种用法import * as obj from,这种写法是把所有的输出包裹到obj对象里。示例一 1 2 3 4 5 6 7 // index.js export function fn1(data){ console.log(1) } export f.
视频讲解关于异步处理,ES5的回调使我们陷入地狱,ES6的Promise使我们脱离魔障,终于、ES7的async-await带我们走向光明。今天就来学习一下 async-await。async-await和Promise的关系经常会看到有了 async-await、promise 还有必要学习吗、async await优于promise的几个特点,接收了这些信息后,就蒙圈了。现在才知道...
TypeScript什么是TypeScript?TypeScript是由微软开发的一款开源的编程语言TypeScript是JavaScript的超集,遵循最新的ES5 ES6规范,TypeScript扩展了JavaScript的语法TypeScript更像后端 Java c# 这样的面向对象语言可以让js开发大型企业项目谷歌也在大力支持TypeScript的推广,React ,VUE 都集成了TypeScriptTypeScript安装安装-- 安装npm install -g type
export class AppComponent { title = 'Tour of heroes'; hero: Hero = { id: 1, name: '张三' };}export class Hero { id: number; name: string;}就是这一段,看起来有点晕,这里是实例化一个Hero类型的对象hero,还是创建一个变量?后面是赋值,但是不知道什么意思?hero: Hero = { id: 1, na.
用 async/await 来处理异步昨天看了一篇vue的教程,作者用async/ await来发送异步请求,从服务端获取数据,代码很简洁,同时async/await 已经被标准化,是时候学习一下了。先说一下async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。 写一个async 函数async function timeout() {return 'hello world'
es6的语法已经出了很长的时间了,在使用上也可以通过babel这类的编译工具转译为浏览器可以识别的es5的语法,但是依旧有很多开发在写代码的时候,依旧没有用es6的语法,而是习惯使用老的语法,这篇文章主要会介绍解构赋值基本用法以及在实际使用场景中相比es5语法的优势,让大家从根本上了解es6语法的优势基本用法数组解构让我们一起先来看数组解构的基本用法:let [a, b, c] ...
参考链接1 参考链接2写法1 - 使用 function 关键字function greeter(fn: (a: string) =&gt; void) { fn("Hello, World");}function printToConsole(s: string) { console.log(s);}greeter(printToConsole);(a: string) =&gt; void上述语法的含义:表示一个函数,接收一个字符串作为输入参数,没有返回参数。可
ES6简介-ECMAScript是javascript标准-ES6就是ECMAScript的第6个版本-ECMAScript6.0(以下简称ES6)是JavaScript语言的下一代标准,已经在2015年6月正式发布了。它的目标,是使得JavaScript语言可以用来编写复杂的大型应用程序,成为企业级开发语言。ES6新增加的功能:1.let
ES6  在ES5的基础上增加了一些新的特性和写法,特别在函数写法上,增加了箭头函数 1.正经的函数写法//普通的传递值的写法functionsum1(x,y){returnx+y;}constres=sum1(2,3);console.log(res);//传递对象的方式,调用时需要传递一个对象过去function
ES5及ES6es表示ECMASCript,他是从es3,es5,es6,es5是2009.12月发布的,es6是2015.6月发布的。vue2完全支持es5的(vue3完全支持es6的),react完全支持es6es5的新特性严格模式(对应的相反的称为怪异模式)'usestrict'//一般用于相关的设计上面书写一个严格模式底下的代码就需要按照严格模
ES5的严格模式所谓严格模式,从字面上就很好理解,即更严格的模式,在这种模式下执行,浏览器会对JS的要求更苛刻,语法格式要求更细致,更符合逻辑。怪异模式:就是我们之前一直使用的开发模式,就叫怪异模式。因为很多时候出来的结果是非常怪异的,所以才称之为怪异模式。'usestrict'//一般用
相同点export与exportdefault均可用于导出常量、函数、文件、模块可在其它文件或模块中通过import+(常量|函数|文件|模块)名的方式,将其导入,以便能够对其进行使用不同点一、在一个文件或模块中,export、import可以有多个,exportdefault仅有一个//model.jsle
24.class类 25.class中的extend 26.super关键字 27.super应用 28.class属性 30.静态成员和实例成员 31.构造函数问题 32.构造函数原型 33.原型链 34.js查找机制 35.原型对象中this指向 36.扩展内置对象方法 37.call方法 38.借用父构造函数
什么是ES6ES的全称是ECMAScript,它是由ECMA国际标准化组织,制定的一项脚本语言的标准化规范。泛指2015年发布的es2015版极其后续版本ES6中新增语法letES6中新增的用于声明变量的关键字。注意:使用let关键字声明的变量才具有块级作用域,使用var声明的变量不具备块级作用域特
命名修饰符let:不能重复声明变量、块级作用域leta=1;leta=2;//报错const:初始化常量,必须给初始值,否则报错、在同一个作用域内,const定义的常量不能修改其值、块级作用域consta=10a=100//报错,不能重复声明解构constobj={name:'jack'age:18sex:'
ES6新增了let命令,用来声明变量。它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效。1{2leta=10;3varb=1;4}56a//ReferenceError:aisnotdefined.7b//1上面代码在代码块之中,分别用let和var声明了两个变量。然后在代码块之外调用
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><metahttp-equiv="X-UA-Compatib
一,RegExp构造函数es5中,RegExp构造函数的参数有两种情况。1,参数是字符串,第二个参数表示正则表达式的修饰符(flag)。2,参数是一个正则表达式,返回一个原有正则表达式的拷贝。es6中,如果RegExp构造函数第一个参数是一个正则对象,那么可以使用第二个参数指定修饰符。而
一、字符的Unicode表示法JavaScript允许采用\uxxxx形式表示一个字符,其中xxxx表示字符的Unicode码点。表示法只限于码点在\u0000~\uFFFF之间的字符,超过该范围需要用两个双字节表示ES6改进:将码点放入大括号,就能正确解读该字符。转换参考:https://blog.csdn.net/hezh1994/ar