1. 程式人生 > 程式設計 >ES6實現圖片切換特效程式碼

ES6實現圖片切換特效程式碼

效果圖

demo.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script type="text/javascript">
    let arr = ["前端","jquery","javascript","html","css"];
    //補充程式碼
    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.innerHTML=lis;
    document.body.appendChild(ul);
  </script>
</body>
</html>

style.css

* {
 margin: 0;
 padding: 0;
}

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

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

#wrap {
 width: 1065px;
 padding-top: 50px;
 margin: 0 auto;
 padding: 30px;
 background: rgb(255,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 {
 display: inline-block;
 padding: .2em 1em;
 font-size: 1.6em;
 margin-right: 10px;
 cursor: pointer;
 border: 1px solid #e95a44;
 outline: none;
 color: #e95a44;
 transition: all .4s;
 user-select: none;
 border-radius: 2px;
}

/* 啟用狀態的分類按鈕 */
.__Img__container .__Img__classify .__Img__classify__type-btn.__Img__type-btn-active {
 background: #e95a44;
 /* border: 1px solid #9b59b6; */
 color: #fff;
}

/* 所有圖片容器 */
.__Img__container .__Img__img-container {
 position: relative;
 margin-top: 30px;
 width: 1005px;
 display: flex;
 flex-wrap: wrap;
 transition: all .6s cubic-bezier(0.77,0.175,1);
}

/* 單個圖片容器 */
.__Img__container .__Img__img-container figure {
 width: 240px;
 height: 140px;
 position: absolute;
 transition: all .6s cubic-bezier(0.77,1);
 transform: scale(0,0);
 opacity: 0;
 overflow: hidden;
 border-radius: 2px;
 user-select: none;
}

/* 偽元素遮罩層 */
.__Img__container .__Img__img-container figure::before {
 display: block;
 position: absolute;
 width: 100%;
 height: 100%;
 top: 0;
 left: 0;
 z-index: 4;
 background: rgba(58,12,5,0.5);
 content: ' ';
 font-size: 0;
 opacity: 0;
 transition: all .3s;
 cursor: pointer;
}

/* 圖片 */
.__Img__container .__Img__img-container figure img {
 display: block;
 width: 100%;
 height: 100%;
 transition: all .3s;
}

/* 圖片標題 */
.__Img__container .__Img__img-container figure figcaption {
 position: absolute;
 top: 50%;
 left: 50%;
 z-index: 7;
 opacity: 0;
 font-size: 1.5em;
 color: rgb(255,255);
 transform: translate(-50%,-50%);
 transition: all .3s;
 text-align: center;
 cursor: pointer;
}

/* 懸停圖片的時候標題顯示 */
.__Img__container .__Img__img-container figure:hover figcaption {
 opacity: 1;
}

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

/* 懸停圖片的時候遮罩顯示 */
.__Img__container .__Img__img-container figure:hover::before {
 opacity: 1;
}

.__Img__overlay {
 position: fixed;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 background-color: rgba(0,.8);
 display: flex;
 justify-content: center;
 align-items: center;
 opacity: 0;
 transition: all .3s;
 display: none;
}

.__Img__overlay .__Img__overlay-prev-btn,.__Img__overlay .__Img__overlay-next-btn {
 position: absolute;
 width: 50px;
 height: 50px;
 border-radius: 50%;
 border: 2px solid white;
 text-align: center;
 line-height: 50px;
 color: white;
 font-size: 2rem;
 cursor: pointer;
}

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

.__Img__overlay .__Img__overlay-next-btn {
 right: 20px;
}

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

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

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

.__Img__overlay img {
 transform: 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);
   },// 選擇多個元素
   $$(selector,root = document) {
    return root.querySelectorAll(selector);
   }
  };

 // 建構函式
  let Img = function(options) {
   // 初始化
    this._init(options);
   // 生成DOM元素
    this._createElement();
   // 繫結事件
    this._bind();
   // 顯示到頁面上
    this._show();
  }

 // 初始化
  Img.prototype._init = function({ data,initType,parasitifer }) {
   this.types = ['全部']; // 所有的分類
   this.all = []; // 所有圖片元素
   this.classified = {'全部': []}; // 按照型別分類後的圖片
   this.curType = initType; // 當前顯示的圖片分類
   this.parasitifer = methods.$(parasitifer); // 掛載點

   this.imgContainer = null; // 所有圖片的容器
   this.wrap = null; // 整體容器
   this.typeBtnEls = null; // 所有分類按鈕組成的陣列
   this.figures = null; // 所有當前顯示的圖片組成的陣列
   // 對圖片進行分類
   this._classify(data);

   //console.log(this.classified);//分類的結果
  };

 // 對圖片進行分類
  Img.prototype._classify = function(data) {
   let srcs = [];
   // 解構賦值,獲取每張圖片的四個資訊
   data.forEach(({ title,type,alt,src }) => {
    // 如果分類中沒有當前圖片的分類,則在全部分類的陣列中新增該分類
    if (!this.types.includes(type)) {
     this.types.push(type);
    }
    // 判斷按照型別分類後的圖片中有沒有當前型別
    if (!Object.keys(this.classified).includes(type)) {
     this.classified[type] = [];
    }
    // 判斷當前圖片是否已生成
    if (!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',alt);
     figcaption.innerText = title;
     // 在figure中新增img和figcaption
     methods.appendChild(figure,img,figcaption);
     // 將生成的figure新增到all陣列中
     this.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 = function(type) {
   // 如果分類是全部,就返回所有圖片
   // 否則,通過map進行遍歷,根據分類來獲取圖片陣列
   return type === '全部' ? [...this.all] : this.classified[type].map(index => this.all[index]);
  };

 // 生成DOM
  Img.prototype._createElement = function() {
   // 建立分類按鈕
   let typesBtn = [];
   // 遍歷分類陣列
   for (let type of this.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',wrap);
    //檢視當前分類下的圖片
    console.log(this._getImgsByType(this.curType));
    // 把當前分類下的圖片陣列,插入到圖片容器裡
    methods.appendChild(this.imgContainer,...this._getImgsByType(this.curType));

    //把可能有用的資料先掛到指定位置
    this.wrap = wrap;
    this.typeBtnEls = [...methods.$$('.__Img__classify__type-btn',wrap)];
    this.figures = [...methods.$$('figure',wrap)];

    // 遮罩層
    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(this.wrap,overlay);
    this.overlay = overlay;
    // 當前要預覽的圖片
    this.previewImg = methods.$('img',overlay);
    // 移動每張圖片到合適的位置
    this._calcPosition(this.figures);
   };

 // 獲取上一次顯示的圖片和下一次顯示的圖片中,相同的圖片下標(對映關係)
  Img.prototype._diff = function(prevImgs,nextImgs) {
   let diffArr = [];//儲存兩次中相同的資料的下標
   //遍歷前一次的所有圖片
   //如果在下一次中存在相同的,則獲取下標index2
   prevImgs.forEach((src1,index1) => {
    let index2 = nextImgs.findIndex(src2 => src1 === src2);

    if (index2 !== -1) {
     // 在這個對映陣列中存入下標
     diffArr.push([index1,index2]);
    }
   });

   return diffArr;
  };

 // 繫結事件
  Img.prototype._bind = function() {
   // 事件代理,點選事件繫結在ul上
    methods.$('.__Img__classify',this.wrap).addEventListener('click',({ target }) => {

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

     if (!canChange) return;
     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',figure).src);//下一次顯示的圖片陣列

     const diffArr = this._diff(prevImgs,nextImgs);//獲取兩次相同圖片的對映關係(下標)

     diffArr.forEach(([,i2]) => {
      // 對下一次的所有圖片進行遍歷
      this.figures.every((figure,index) => {
       let src = methods.$('img',figure).src;
       // 如果下一次的圖片在這一次中已經出現過
       if (src === nextImgs[i2]) {
        // 則從所有圖片陣列中剔除該圖片(從Index位置,裁剪1個)
        this.figures.splice(index,1);
        return false;
       }
       return true;
      });
     });
     // 計算圖片位置
     this._calcPosition(els);

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

      els.forEach((figure,index) => {
       // 如果該圖片沒有出現過,則需要插入
       if (!nextElsIndex.includes(index)) needAppendEls.push(figure);
      });

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

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

     // 把下一次需要顯示的圖片新增到圖片容器中
     methods.appendChild(this.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 => {
       this.imgContainer.removeChild(figure);
      });

      this.figures = els;
      canChange = true;
      // 保證在一次切換動畫沒有完成之前,拒絕進行下一次切換
      // 避免快速切換
     },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',({ target }) => {
     // 如果點選的不是圖片或者圖片描述,則返回
     if (target.nodeName !== 'FIGURE' && target.nodeName !== 'FIGCAPTION') return;

     // 如果點選的是圖片的描述
     // 則把target轉為其父元素圖片
     if (target.nodeName === 'FIGCAPTION') {
      target = target.parentNode;
     }

     const src = methods.$('img',target).src;

     // 拿到當前圖片索引
     curPreviewImgIndex = this.figures.findIndex(figure => src === methods.$('img',figure).src);

     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',this.overlay).addEventListener('click',e => {

     e.stopPropagation();//阻止事件冒泡
     // 如果是第一張,上一張就是最後一張
     curPreviewImgIndex = curPreviewImgIndex === 0 ? this.figures.length - 1 : curPreviewImgIndex - 1;
     // 獲取到需要上一張顯示的圖片的src,賦值給預覽圖的src
     this.previewImg.src = methods.$('img',this.figures[curPreviewImgIndex]).src;
    });

   // 預覽點選切換下一張
    methods.$('.__Img__overlay-next-btn',e => {

     e.stopPropagation();
     // 如果是最後一張,下一張就是第一張
     curPreviewImgIndex = curPreviewImgIndex === this.figures.length - 1 ? 0 : curPreviewImgIndex + 1;
     this.previewImg.src = methods.$('img',this.figures[curPreviewImgIndex]).src;
    });

  };

 // 顯示元素
  Img.prototype._show = function() {
   methods.appendChild(this.parasitifer,this.wrap);

   //設定出現的動畫效果
   setTimeout(() => {
    this.figures.forEach(figure => {
     figure.style.transform = 'scale(1,0)';
     figure.style.opacity = '1';
    });
   });
  };

 // 計算每張圖片所佔的位置
  Img.prototype._calcPosition = function(figures) {
   let horizontalImgIndex = 0;

   figures.forEach((figure,index) => {
    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',title: 'ES6快速入門',alt: 'ES6快速入門',src: './assets/images/1.jpg'
 },{
  type: 'JavaScript',title: 'Javascript實現二叉樹演算法',alt: 'Javascript實現二叉樹演算法',src: './assets/images/2.jpg'
 },title: 'Canvas繪製時鐘',alt: 'Canvas繪製時鐘',src: './assets/images/3.jpg'
 },title: '基於websocket的火拼俄羅斯',alt: '基於websocket的火拼俄羅斯',src: './assets/images/15.jpg'
 },{
  type: '前端框架',title: 'React知識點綜合運用例項',alt: 'React知識點綜合運用例項',src: './assets/images/4.jpg'
 },title: 'React元件',alt: 'React元件',src: './assets/images/5.jpg'
 },title: 'Vue+Webpack打造todo應用',alt: 'Vue+Webpack打造todo應用',src: './assets/images/6.jpg'
 },title: 'Vue.js入門基礎',alt: 'Vue.js入門基礎',src: './assets/images/7.jpg'
 },title: '使用Vue2.0實現購物車和地址選配功能',alt: '使用Vue2.0實現購物車和地址選配功能',src: './assets/images/8.jpg'
 },{
  type: 'React',{
  type: 'Vue.js',src: './assets/images/8.jpg'
 }

]

總結

以上所述是小編給大家介紹的ES6實現圖片切換特效程式碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!