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

How to add a next and previous link to current slider in javascript?

本文关键字:添加 链接 上一个 javascript 下一个      更新时间:2023-10-20

我已经做了一整天了。我是个笨蛋,所以很沮丧。我想知道如何在下面的滑块中添加上一个和下一个链接。我想在纯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初始化,但它能工作。。。还要注意,现在没有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;
}

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