原生javascript+CSS實現輪播圖效果

本文實例為大傢分享瞭javascript+CSS實現輪播圖效果的具體代碼,供大傢參考,具體內容如下

1.html

<ul id="banner" ></ul>

2.css

ul{
    list-style:none;
    position: absolute;
    padding: 0;
    left: 0;
    right: 0;
    bottom: 0;
    top:0;
    margin:auto;
    width: 800px;
    height:200px;
}

3.js

//生成輪播圖
export function generateBanner(){
  let sz = new Array();
  let cur_ul = document.getElementById('banner');
  const recommends = this.recommends;

  let timer = setInterval(getNextLi, 3000);

  //生成輪播圖li
  for (let i = 0; i < recommends.length; i++) {
    //生成標簽
    let cur_li = document.createElement("li");
    let cur_img = document.createElement("img");
    //追加屬性
    cur_img.src = recommends[i].pic;
    //追加樣式
    cur_li.style.position = 'absolute';
    cur_li.style.left = '0px';
    cur_li.style.transitionDuration = '0.4s';
    cur_li.style.cursor="pointer";

    //ul總寬800 ,顯示一張完整的400px 兩張不完整的200px
    cur_img.style.width = '125px';
    cur_img.style.height = "100px";

    //追加子元素
    cur_li.appendChild(cur_img);
    cur_ul.appendChild(cur_li);

    //全部放入數組好操作
    sz.push(cur_li);
  }

  //生成兩個圖標
  generateAngleIcons();

  //將最後三張圖片用來顯示
  let len = sz.length - 1;
  //倒數第三張
  showThreeLi();

  //獲取下一個li顯示,將第一個放到數組最後
  function getNextLi() {
    const li = sz[0];
    sz = sz.slice(1);
    sz.push(li);

    //所有li還原
    for (let i = 0; i < sz.length; i++) {
      //li全部還原成原始大小
      sz[i].style.transform = "scale(1)";
      sz[i].style.left = "0px";
      //從小到大li依此覆蓋
      sz[i].style.zIndex = i;

      //全部隱藏
      sz[i].style.display = "none";
    }
    //顯示最後三張
    showThreeLi();

  }

  //顯示最後三張
  function showThreeLi() {
    sz[len - 2].style.left = "0px";
    //倒數第二張
    sz[len - 1].style.left = "120px";
    sz[len - 1].style.zIndex = 100;
    sz[len - 1].style.transform = "scale(1.3)";
    //倒數第一張
    sz[len].style.left = "230px";

    //顯示
    sz[len - 2].style.display = "block";
    sz[len - 1].style.display = "block";
    sz[len].style.display = "block";
  }


  function generateAngleIcons(){
    const icons = new Array();

    for (let i = 0; i < 2; i++) {
      //生成圖標li
      let cur_li = document.createElement("li");
      //追加樣式
      cur_li.style.position = 'absolute';
      cur_li.style.top = '0px';
      cur_li.style.bottom = '0px';
      cur_li.style.margin = "auto";
      cur_li.style.paddingTop="100px";
      cur_li.style.paddingBottom="100px";
      cur_li.style.zIndex = 20;
      icons.push(cur_li);
    }

    icons[0].style.left = '0px';
    icons[1].style.right = '0px';
    icons[0].innerHTML = '<i class="angle left icon"></i>'
    icons[1].innerHTML = '<i class="angle right icon"></i>'
    cur_ul.appendChild(icons[1]);
    cur_ul.appendChild(icons[0]);
  }
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: