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

<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
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)
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)
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)"
}
]