HTML
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="window">
<div class="images" id="images">
<img src="https://fthmb.tqn.com/0ui_Zw01Ht9NHJkSBlqOIC1IH44=/960x0/filters:no_upscale()/yorkshire-terrier-583788122-581630e85f9b581c0b018a00.jpg" width=300 alt="图片1" height=200>
<img src="https://canna-pet.com/wp-content/uploads/2017/06/20-longest-living-dog-breeds_canna-pet-e1498599846169.jpg" width=300 alt="" height=200>
<img src="https://fthmb.tqn.com/0ui_Zw01Ht9NHJkSBlqOIC1IH44=/960x0/filters:no_upscale()/yorkshire-terrier-583788122-581630e85f9b581c0b018a00.jpg" width=300 alt="" height=200>
<img src="https://canna-pet.com/wp-content/uploads/2017/06/20-longest-living-dog-breeds_canna-pet-e1498599846169.jpg" width=300 alt="" height=200>
</div>
</div>
<div id="buttons">
<button>第1张</button>
<button>第2张</button>
<button>第3张</button>
<button>第4张</button>
</div>
</body>
</html>
JS
var allButtons = $('button')
for(let i=0; i<allButtons.length; i++){
//JQ遍历点击事件
$(allButtons[i]).on('click', function(x){
//currentTarget:选择当前点击对象。index():在兄弟中排第几位
var index = $(x.currentTarget).index()
var p = index * -300
//transform:位移。translate:移动距离
$('#images').css({
transform: 'translate('+ p + 'px)'
})
n =index
//eq:JQuery将DOM对象封装成JQ对象,可直接进行JQ操作,不用二次封装。siblings:兄弟元素
//allButtons.eq(n).addClass('red').siblings('.red').removeClass('red')
activeButton(allButtons.eq(n))
})
}
var n = 0;
var size = allButtons.length
//trigger:后面可以接任何事件名,比click功能强大。
allButtons.eq(n % size).trigger('click')
var timerId = setTimer()
function setTimer() {
return setInterval(()=>{
n +=1
allButtons.eq(n % size).trigger('click')
},1500)
}
function activeButton($button) {
$button.addClass('red').siblings('.red').removeClass('red')
}
//mouseenter:鼠标进入被选元素
$('.window').on('mouseenter', function(){
window.clearInterval(timerId)
})
//mouseleave:鼠标离开被选元素
$('.window').on('mouseleave', function(){
timerId = setTimer()
})
CSS
.window{
width: 300px;
overflow: hidden;
}
.images{
display: flex;
transition: all .5s;
}
.red{
color: red;
}
#buttons{
margin-top: 10px;
}
button{
cursor: pointer;
}