我正在写vanillaJS滑块。当我刷新网站有时它的工作很好,有时候不行。在Codepen / Snippet代码上工作完美。
const activeEl = document.getElementsByClassName('active')[0];
const slideList = document.getElementsByClassName('slide-unit');
let activeElIndex = Array.from(activeEl.parentNode.children).indexOf(activeEl);
function sliderFunction(newActiveElIndex){
if (newActiveElIndex != activeElIndex){
slideList[activeElIndex].classList.remove('active');
slideList[newActiveElIndex].classList.add('active');
activeElIndex = newActiveElIndex;
}
for (let i = 0; i < slideList.length; i++){
if (newActiveElIndex < i){
slideList[i].style.left = (i-newActiveElIndex-1)*21.25 + 36.25 +"vw";
} else if (newActiveElIndex > i){
slideList[i].style.left = (i-newActiveElIndex)*21.25 +"vw";
} else {
slideList[i].style.left = 0 +"vw";
}
}
}
sliderFunction(activeElIndex);
for (let i = 0; i < slideList.length; i++){
slideList[i].addEventListener('click', function(){sliderFunction(i);}, false);
}
.slider {
position: relative;
height: 45vh;
width: 30vw;
margin: 0 35vw 0 35vw; }
.slider .slide-unit {
position: absolute;
height: 50%;
width: 50%;
top: 25%;
left: 0;
background-color: pink;
transition: all 800ms cubic-bezier(0.68, -0.55, 0.265, 1.55); }
.slider .slide-unit.active {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0; }
<div class="slider">
<div class="slide-unit"></div>
<div class="slide-unit active"></div>
<div class="slide-unit"></div>
<div class="slide-unit"></div>
<div class="slide-unit"></div>
<div class="slide-unit"></div>
</div>
活动(较大)元素应位于中心。这是某种错误还是我的错误?