在图像滑块中实现导航

问题描述 投票:0回答:1

我想在图像滑块中实现一个简单的左右箭头导航。以下是我已经尝试过的。如果单击箭头,我必须在哪里放置该功能。在changeImg功能的内部或外部?提前致谢

    <div class="slider">
        <span id="left">&lt</span>
        <img class="sliderImg" name="slide">
        <span id="right">&gt</span>
    </div>

    var i = 0;
    var images = [];
    var time = 4000;

    images[0] = "img/image1.png";
    images[1] = "img/image2.png";
    images[2] = "img/image3.png";

    function changeImg() {
        document.slide.src = images[i];

        if (i < images.length - 1) {
            i++;
        }

        document.querySelector("#left").addEventListener("click", function()
        {
            i--;
        });

        else {
            i = 0;
        }
        setTimeout("changeImg()", time);
    }
javascript html slider
1个回答
0
投票

你可以这样做:

HTML

<div class="container">
    <div id="slideshow">
        <img alt="slideshow" src="img/image1.png" id="imgClickAndChange" onclick="changeImage()" />
    </div>
    <span id="left-arrow">left</span>
      <span id="right-arrow">right</span>

</div>

使用Javascript:

 var imgs = ["img/image2.png", "img/image3.png", "img/image4.png"];

    function changeImage(dir) {
        var img = document.getElementById("imgClickAndChange");
        img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];
    }

    var left=document.getElementById('left-arrow');
   var right=document.getElementById('right-arrow');
    left.onclick = function(e) {

            changeImage(-1) //left <- show Prev image

    }
     right.onclick = function(e) {

            changeImage() //left <- show Prev image

    }

使用正确的图像路径

© www.soinside.com 2019 - 2024. All rights reserved.