繁体   English   中英

纯JS的水平滑块

[英]Horizontal slider with pure JS

我有一个愚蠢而简单的问题,但我是JS的初学者。 我想创建一个水平滑块。 现在JS代码看起来像这样:

var slideIndex = 0;
slider();

function slider() {
var i;
var x = document.getElementsByClassName("part");
for (i = 0; i < x.length; i++) {
  x[i].style.display = "none"; 
}

slideIndex++;
if (slideIndex > x.length) {slideIndex = 1} 
x[slideIndex-1].style.display = "inline"; 
setTimeout(slider, 3000);

}

我知道我应该使用marginLeft属性使图像从左到右显示,但我不知道如何在代码中使用此属性。 任何帮助/提示将非常感谢!

HTML代码:

     <div class="container">
                <section class="content"> 
                        <div id="img1" class="slide">
                            <h2>...</h2>
                            <p>....</p>
                        </div>
                        <div id="img2" class="slide">
                            <h2>....</h2>
                            <p>....</p>
                        </div>
                </section>
            </div>

也许你可以添加一个“slideOut”动画类

  var slideIndex = 0; slider(); function slider() { var i; var x = document.getElementsByClassName("part"); for (i = 0; i < x.length; i++) { x[i].classList.remove("slide"); x[i].classList.remove("slideOut"); x[i].className += " slideOut"; } slideIndex++; if (slideIndex > x.length) { slideIndex = 1 } x[slideIndex - 1].classList.remove("slideOut"); x[slideIndex - 1].style.display = "inline"; x[slideIndex - 1].className += " slide"; setTimeout(slider, 1500); } 
  .content { position: relative; width: 100px; height: 100px; overflow: auto; } .row { margin: 0 auto; width: 50%; } .slide { position: absolute; left: -100px; width: 100px; height: 100px; -webkit-animation: slide 0.5s forwards; -webkit-animation-delay: 0.5s; animation: slide 0.5s forwards; animation-delay: 0.5s; } @-webkit-keyframes slide { 100% { left: 0; } } @keyframes slide { 100% { left: 0; } } .slideOut { position: absolute; left: 0px; width: 100px; height: 100px; -webkit-animation: slideOut 0.5s forwards; -webkit-animation-delay: 0.5s; animation: slideOut 0.5s forwards; animation-delay: 0.5s; } @-webkit-keyframes slideOut { 100% { left: 100px; } } @keyframes slideOut { 100% { left: 100px; } } #img1 { background: red; text-align: center } #img2 { background: blue; text-align: center } #img3 { background: greenyellow; text-align: center } #img4 { background: orangered; text-align: center } 
 <div class="row"> <section class="content"> <div id="img1" class="part"><img src="" alt=""> <h3>1</h3></div> <div id="img2" class="part"><img src="" alt=""> <h3>2</h3></div> <div id="img3" class="part"><img src="" alt=""> <h3>3</h3></div> <div id="img4" class="part"><img src="" alt=""> <h3>4</h3></div> </section> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM