console
window.onload = () => {
let list = document.getElementsByClassName("Wrapper")[0].children;
const indexMax = list.length - 1;
let activeIndex;
for(let i = 0; i <= indexMax;i++){
list[i].onclick=(e)=>handleChange("onclick",e);
}
}
const handleChange= (type="onclick", event) =>{
let list = document.getElementsByClassName("Wrapper")[0].children;
const indexMax = list.length - 1;
let activeIndex;
for(let i = 0; i <= indexMax;i++){
let itemClassList = list[i].className;
if(itemClassList.indexOf("active")>-1){
activeIndex = i;
}
}
if(type==="right"){
if(activeIndex < indexMax){
list[activeIndex].setAttribute('class','item')
list[activeIndex + 1].setAttribute('class','item active')
list[activeIndex + 1].scrollIntoView({behavior: "smooth"})
}
}
else if(type==="left"){
if(activeIndex > 0){
list[activeIndex].setAttribute('class','item')
list[activeIndex -1].setAttribute('class','item active')
list[activeIndex -1].scrollIntoView({behavior: "smooth"})
}
}else {
list[activeIndex].setAttribute('class','item')
event.target.setAttribute('class','item active')
event.target.scrollIntoView({behavior: "smooth"})
}
}
<div class="father">
<button class="btn btn-left" onclick="handleChange('left')">左</button>
<div class="Wrapper">
<div class="item active" id="item1">我是1</div>
<div class="item" id="item2">我是2</div>
<div class="item" id="item3">我是3</div>
<div class="item" id="item4">我是4</div>
<div class="item" id="item5">我是5</div>
<div class="item" id="item6">我是6</div>
<div class="item" id="item7">我是7</div>
<div class="item" id="item8">我是8</div>
<div class="item" id="item9">我是9</div>
<div class="item" id="item10">我是10</div>
<div class="item" id="item11">我是11</div>
<div class="item" id="item12">我是12</div>
</div>
<button class="btn btn-right" onclick="handleChange('right')">右</button>
</div>
.Wrapper {
background: #fff;
height: 200px;
display: flex;
}
.item{
margin-right: 20px;
background: grey;
width: 100px;
flex-shrink:0;
}
.item:last-child{
margin-right: 0
}
.item.active {
background: red;
}
.father {
position: relative;
display: inline-flex;
align-items: center;
justify-content: space-between;
overflow-x: scroll;
width: 500px;
}
.btn {
width: 50px;
height: 50px;
}
.btn-left {
position: sticky;
left: 0;
}
.btn-right {
position: sticky;
right: 0;
}