首页推荐

77 阅读2分钟

思路

  • 首先获取元素,创建活跃状态,创建数组保存数据
  • 根据data获取每个元素,生成标签,属性,循环遍历出来,并且保存到数组中
  • 根据侧边栏鼠标移入,通过闭包方式,清除定时器,让他不自动播放,首先移除之前活跃的状态,根据当前索引,设置成为活跃状态
  • 鼠标移出恢复定时器
  • 通过定时器让其自动滚动,首先移除之前的活跃状态,其次判断当前索引是否是最后一个,最后一个就把索引设置为第一个,不是就索引加一;最后设置成活跃状态

效果图

image.png

  <div class="content">
    <div class="top-nav"></div>
    <div class="imgs" id="imgs">
    </div>
    <div class="side-bar" id="side-bar">
      <a href="#" class="cnhz">
        <img src="./img/all.png" alt="">
        猜你会追
      </a>
      <a href="#" class="zbtj">
        <img src="./img/tj.png" alt="">
        重磅推荐
      </a>
    </div>
  </div>
// 获取元素
var imgs = document.getElementById('imgs')
var sideBar = document.getElementById('side-bar')

// 存储数据
var imgsDom = []
var navDom = []

// 记录当前图片是否活跃
var activeImg = null
var activeNav = null

// 根据data数组 生成对应的图片和元素
for (var i = 0; i < data.length; i++){
  var item = data[i]
  // 创建图片
  var tagA = document.createElement('a')
  tagA.setAttribute('href', '#')
  tagA.style.backgroundColor = item.bg
  tagA.style.backgroundImage = 'url('+item.img+')'
  imgs.appendChild(tagA)
  imgsDom.push(tagA)

  // 创建导航
  var tagNav = document.createElement('a')
  tagNav.setAttribute('class', 'nav')
  tagNav.setAttribute('href', '#')
  tagNav.setAttribute('title', item.title + ':' + item.desc)
  tagNav.innerHTML = '<span>'+item.title+'</span>'
  sideBar.appendChild(tagNav)
  navDom.push(tagNav)

  // 当索引为0的时候 状态设置为活跃的
  if (i === 0) {
    tagA.setAttribute('class', 'active')
    tagNav.setAttribute('class', 'active')
    activeImg = tagA
    activeNav = tagNav
  }

  tagNav.onmouseenter = (function (tagA, tagNav) {
    return function () {
      // 当鼠标移入的时候清除定时器
      clearInterval(carousel)
      // 将原来活跃的图片移除
      activeImg.setAttribute('class', '')
      activeNav.setAttribute('class', 'nav')

      // 把当前的鼠标选中的进行展示
      tagA.setAttribute('class', 'active')
      tagNav.setAttribute('class', 'active')

      // 记录最新的导航和图片
      activeImg = tagA
      activeNav = tagNav
    }
  })(tagA, tagNav)

  // 鼠标移除的时候,恢复定时器
  tagNav.onmouseleave = function () {
    carousel = setInterval(move, 3000)
  }
}

// 轮播图
function move() {
  // 将原来的活跃状态移除
  activeImg.setAttribute('class', '')
  activeNav.setAttribute('class', 'nav')

  var index = imgsDom.indexOf(activeImg)

  // 获取当前索引,并奖当前索引设置为活跃状态
  if (index === data.length - 1) {
    activeImg = imgsDom[0]
    activeNav = navDom[0]
  } else {
    activeImg = imgsDom[index + 1]
    activeNav = navDom[index + 1]
  }

  // 将图片和导航设置为活跃状态
  activeImg.setAttribute('class', 'active')
  activeNav.setAttribute('class', 'active')
}

var carousel = setInterval(move, 3000)
// data 部分数据
var data = [
  {
      title: "三十而已",
      desc: "话题爽剧!姐姐飒气挑战",
      img: "https://puui.qpic.cn/media_img/lena/PICgthm4a_580_1680/0",
      bg: "rgb(25,117,180)"
  },
  {
      title: "明子·更新",
      desc: "唢呐版《倍爽儿》超嗨",
      img: "https://puui.qpic.cn/media_img/lena/PICvqg2sg_580_1680/0",
      bg: "rgb(1, 9, 30)"
  }
]