我正在尝试创建简单的普通Javascript滑块,但遇到了一些问题,希望有人可以帮助我。

html代码:

<div class="box" id="boxid">
        <div class="inside_box" id="inside_box_id">
            <ul class="main_ul" id="main_ul_id">
                <li class="one" id="oneid"><a href = "#"></a></li>
                <li class="one" id="twoid"><a href = "#"></a></li>
                <li class="one" id="threeid"><a href = "#"></a></li>
                <li class="one" id="fourid"><a href = "#"></a></li>
                <li class="one" id="fiveid"><a href = "#"></a></li>
            </ul>
        </div> <!-- end of inside_box -->
    </div><!-- end of box -->

    <button id="previd" class="btn">Prev</button>
    <button id="nextid" class="btn">Next</button>


CSS代码:

body {
    background:grey;
    font-family: sans-serif;
}

.box {
    width:800px;
    height:300px;
    border:1px solid black;
    margin: 0 auto;
}

.inside_box {
    width:800px;
    height:300px;
    padding:0px;
    margin:0px;
    overflow: hidden;
}

.main_ul {
    width:4000px;
    padding:0px;
    margin:0px;
}

.main_ul li {
    list-style: none;
    float:left;
}

.one {
    width:800px;
    height:300px;
}

#oneid {background:blue;}
#twoid {background:orange;}
#threeid {background:brown;}
#fourid {background:green;}
#fiveid {background:purple;}


.btn {
    padding:10px;
    width:100px;
    margin-left:50%;
    cursor: pointer;
    margin-top:10px;
}


JS代码

var prevBtn = document.getElementById("previd");
var nextBtn = document.getElementById("nextid");

nextBtn.addEventListener("click", function(){
    var slideLeft = document.getElementById("main_ul_id");
    slideLeft.style.marginLeft = "-800px";
}, false);


目前,当我单击“下一步”按钮时,它将带我到第二张幻灯片,但是当我再次单击它时,它什么也没做。每次单击时如何将其单击以向左空白800px方向移动?

谢谢。

最佳答案

您需要获取当前值并从中减去-800px

第一次单击“下一步”按钮时,会将margin-left设置为-800px,然后看到结果。但是对于下一次按下,它将再次将margin-left设置为-800px

如下所示:

nextBtn.addEventListener("click", function() {
  var slideLeft = document.getElementById("main_ul_id");
  var style = slideLeft.style;
  var totalImages = 5;
  var margin = 800;

  style.marginLeft = (parseInt(style.marginLeft || "0") - margin)%(totalImages*margin) + "px";
}, false);


(totalImages*margin)取余数将在最后一张幻灯片上击中下一张后带来第一张幻灯片。不是最佳逻辑,而只是给您一个想法。

这是工作中的JSFiddle:https://jsfiddle.net/dsa3du93/7/

10-05 21:55