0

你好,

我正在做一个带有 javascript 滑块的网站。我只想将一个文件夹中的特定图像用于滑块,而不是 DOM 中的所有 img。因为我添加了更多不应该成为滑块一部分的 img....

我正在使用这个脚本:

$(function(){
  var i= 0;
  //when the next button is clicked on
  $('.next').on("click", function(){
    //increase the display picture index by 1
    i = i + 1;
    //if we are at the end of the image queue, set the index back to 0
    if (i == $('img').length) {
      i=0;
    }
    //set current image and previous image
    var currentImg = $('img').eq(i);
    var prevImg = $('img').eq(i-1);
    //call function to animate the rotation of the images to the right
    animateImage(prevImg, currentImg);  
  });
  //when the previous button is clicked on
  $('.previous').on("click", function(){
    //if we are at the beginning of the image queue, set the previous image to the first image and the current image to the last image of the queue
    if (i==0) { 
      prevImg = $('img').eq(0);
      i=$('img').length-1;
      currentImg = $('img').eq(i);
    }
    //decrease the display picture index by 1
    else {
      i=i-1;
      //set current and previous images
      currentImg = $('img').eq(i);
      prevImg = $('img').eq(i+1);
    }
    //call function to animate the rotation of the images to the left
    animateImageLeft(prevImg, currentImg);  
  });
  //function to animate the rotation of the images to the left
  function animateImageLeft(prevImg, currentImg) {
    //move the image to be displayed off the visible container to the right
    currentImg.css({"left":"100%"});
    //slide the image to be displayed from off the container onto the visible container to make it slide from the right to left
    currentImg.animate({"left":"0%"}, 1000);
    //slide the previous image off the container from right to left
    prevImg.animate({"left":"-100%"}, 1000);
  }
  //function to animate the rotation of the images to the right
  function animateImage(prevImg, currentImg) {
    //move the image to be displayed off the container to the left
    currentImg.css({"left":"-100%"});
    //slide the image to be displayed from off the container onto the container to make it slide from left to right
    currentImg.animate({"left":"0%"}, 1000);
    //slide the image from on the container to off the container to make it slide from left to right
    prevImg.animate({"left":"100%"}, 1000); 
  }
});

感谢您的任何帮助!

4

1 回答 1

1

$('img')不要在每次需要图像列表时调用,而是维护要显示的图像数组。例如,如果您可以为滑块提供所有 img 标签,class="slider-img"以使选择更容易。

var imgs = $('img.slider-img');

$('img')在您的代码中替换为imgs.

或者,如果您想要从特定网址或“文件夹”提供的所有图像中,您可以执行以下操作:

var address = "example.com/silder_imgs";
var imgs = $('img').filter(function() { return $(this).attr(a).includes(address) });
于 2020-01-11T14:26:58.163 回答