循环浏览变量图像

问题描述 投票:-2回答:2

我目前正在学习基本的JavaScript / JQuery,但是我需要快速解决这个问题,而这个问题现在已经超出了我目前所能解决的范围。

[我正在寻找一种允许我点击图像的功能,当我单击最后一张图像时,它将循环返回到第一张图像。

((我正在尝试做出类似以下内容:https://www.antennebooks.com/product/east-end-of-europe/

任何帮助将不胜感激!

这是我到目前为止所拥有的:

<script>
var images = [
  "images/img1.png",
  "images/img2.png",
  "images/img3.png",
  "images/img4.png"
]

var step = 0;
changeImage(); 

function changeImage() {

  document.getElementById('imgClickAndChange').src = images[step];
  step++;
}
javascript jquery
2个回答
0
投票

我们可以使用jQuery并通过事件来操作DOM,在这种情况下这更有意义。当用户单击图像时,可能会触发“单击”事件。您可以将图像存储在集合中,并且当单击次数大于集合的长度时,显示第一张卡片并重新开始该过程。这是利用jQuery库的JavaScript代码的示例:

$(document).ready(function (){
    var card = $('.card'); //store each card with an image in it in a set
    card.css('cursor', 'pointer'); //set the cursor to pointer to make a click obvious to user
    card.not(':first').hide(); //hide all but the first image (card)
    count = 1; //set the initial click count to one

    card.on('click', function() { //listen for an image to be clicked
        $(this).hide(); //hide the image that has been clicked
        $(this).next().show(); //show the next image
        count++; //increment the count
        if(count > card.length) { //if the count is greater than the length of the set, you are out of images (cards)
            count = 1; //reset the count
            card.first().show(); //show the first card and start process over
        }
    });
});

这是我用来模拟您正在寻找的事件的html代码:

<div class="card" style="max-width: 18rem;">
    <img class="card-img-top" src="/path">
    <div class="card-body">
      <p>This is a random card and stuff</p>
    </div>
 </div>
 <div class="card" style="max-width: 18rem;">
    <img class="card-img-top" src="/path">
    <div class="card-body">
      <p>This is a random card and stuff</p>
    </div>
  </div>
  <div class="card" style="max-width: 18rem;">
    <img class="card-img-top" src="/path">
    <div class="card-body">
      <p>This is a random card and stuff</p>
    </div>
  </div>

如您所见,我们有3张卡片基本上存储了我们的图像。如果只需要图像而不需要卡片,则可以这样做,因为其中的一部分微不足道。这里重要的是编程逻辑。我只是简单地设置一个计数器,一旦该计数器大于卡的集合(集合)的长度(一个集合/集合是一个数组链接对象),然后再次显示第一张卡并按照我向您展示的步骤重新开始在JavaScript中。


0
投票

假设您单击显示的图像时调用了changeImage()函数,只需将step++;更改为step = (step + 1) % images.length;并将其作为函数的第一行即可。每个时间步等于images.length,步将重置为0。

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