原生javascript+CSS实现轮播图效果

编辑: admin 分类: javascript 发布时间: 2022-01-01 来源:互联网

本文实例为大家分享了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";
    //倒数第二张
【转自:http://www.1234xp.com/xggf.html 欢迎转载】    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]);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持hwidc。