如何在javascript中添加下一个和上一个链接到当前滑块?

时间:2013-11-27 00:13:19

标签: javascript html dom

好吧,我整天都在这里。我是一个菜鸟,所以令人沮丧。我想知道如何在下面的滑块中添加上一个和下一个链接。我想在纯javascript没有jquery库中做所有事情。无论如何这里是代码。我觉得我尝试了一切。这在JQuery中要容易得多,但我需要更好地学习纯JavaScript。

<div id="container" onmouseover="stopFunc();" onmouseout="resumeFunc();">
   <img src="#" width="250px" height="145px" id="Box" style="margin: 15px;">
   <div id="imageDesc" style="margin: 15px;"></div>

   <a href="JavaScript:previousImage()" id="prevlink">Previous</a>
   <a href="JavaScript:nextImage()" id="nextlink">Next</a>

</div><!-- End container -->



<script type="text/javascript">
    var imageDescription = document.getElementById("imageDesc");
    var featureImg = document.getElementById("Box");

    var index = 0;

    var imageArray = [
        {src:"images/image1.jpg", des:"description1"},
        {src:"images/image2.jpg", des:"description2"},
        {src:"images/image3.jpg", des:"description3"},
        {src:"images/image4.jpg", des:"description4"}
        ];



    function newImage() {
        document.getElementById("container").style.visibility="visible";

        featureImg.setAttribute("src", imageArray[index].src);
        imageDescription.innerHTML = imageArray[index].des;

        index++;

        if (index >= imageArray.length) {
            index = 0;
        }

    }


    var myTimerControl = setInterval(function(){newImage()},3000);

    function stopFunc() {
        clearInterval(myTimerControl);
    }

    function resumeFunc() {
        myTimerControl = setInterval(function() {newImage()}, 3000);
    }

</script>

1 个答案:

答案 0 :(得分:1)

这有点傻,因为它初始化为-1但是它有效...还要注意现在没有 nextImage()函数,你只需重用newImage()

<a href="JavaScript:newImage()" id="nextlink">Next</a>

...

var imageDescription = document.getElementById("imageDesc");
var featureImg = document.getElementById("Box");

var index = -1;

var imageArray = [
    {src:"images/image1.jpg", des:"description1"},
    {src:"images/image2.jpg", des:"description2"},
    {src:"images/image3.jpg", des:"description3"},
    {src:"images/image4.jpg", des:"description4"}
    ];

newImage();

function newImage() {

    index++;

    if (index >= imageArray.length) {
        index = 0;
    }

    document.getElementById("container").style.visibility="visible";

    featureImg.setAttribute("src", imageArray[index].src);
    imageDescription.innerHTML = imageArray[index].des;

}

function previousImage() {

    index--;

    if (index < 0) {
        index = imageArray.length-1;
    }

    featureImg.setAttribute("src", imageArray[index].src);
    imageDescription.innerHTML = imageArray[index].des;

}

它立即调用新图像,这意味着您不必等待第一个计时器运行才能看到图像。您还可以重构一下以使其更简单,但主要概念是 - 在显示之前增加/减少索引使其更清晰,否则您当前的索引值不代表实际显示的内容。