javascript - 使 jQuery 图像 slider 停在最后一张图像并添加下一个和上一个按钮

标签 javascript jquery html css

我有以下示例,它遍历每个 LI,如果您将鼠标悬停,图像将暂停,并在您鼠标移出时继续,但这是我所能得到的。

我希望它在到达最后一个 LI 时停止,并且还想让我添加的 2 个链接带有类“下一个”和“上一个”,因此如果单击将移动到下一个或上一个图像。当然,如果在第一张图片上将上一张图片设置为隐藏类,如果在最后一张图片上将下一张按钮设置为隐藏,则无法使用,但这是我所知道的。

$( function() {
  var timer;
      lis = $(".productImage");
  
  function showNext() {    
    var active = lis.filter(".active").removeClass("active");
    var next = active.next();
    if (next.length===0) {
      next = lis.eq(0);  
    }
    next.addClass("active");    
  }
  
  function showPrev() {    
    var active = lis.filter(".active").removeClass("active");
    var prev = active.prev();
    if (prev.length===0) {
      prev = lis.eq(0);  
    }
    prev.addClass("active");    
  }

  function playGallery() {
    stopGallery();
    timer = window.setInterval(showNext, 2500);
  }

  function stopGallery() { 
    if (timer) window.clearTimeout(timer);
  }
  
  // move to next image
  $('.galleryNext').on('click', function(event){
    stopGallery();
    showNext();
  });

  // move to previous image
  $('.galleryPrev').on('click', function(event){
    stopGallery();
    showPrev();
  });
  
  // reset slider timer if thumbnail changed
  $('.thumbnail-list li a').on('click', function(event){
    stopGallery();
    playGallery();
  });
  
  // pause image slider if mouse is hovering gallery main image
  $(".featured-image-list")
    .on("mouseleave", playGallery)
    .on("mouseenter", stopGallery);

  playGallery();
  
});
.productImage {
    display : none;  
}

.productImage.active {
    display: block;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="featured-image-list">
  <li class="productImage active">1</li>
  <li class="productImage">2</li>
  <li class="productImage">3</li>
  <li class="productImage">4</li>
  <li class="productImage">5</li>
</ul>
<a class="galleryPrev">prev</a>
<a class="galleryNext">next</a>

最佳答案

修改你的代码是我想出的最低限度:

JSFIDDLE

只需将 showNext() 和 showPrev() 放在下面的函数中即可获得下一个和上一个按钮,但需要注意的是它还会阻止幻灯片自动播放(我在你的编辑中看到你所做的):

function nextImage() {
  stopGallery();
  showNext();
}

function prevImage() {
  stopGallery();
  showPrev();
}

我会留给你想出一个解决方案。

您还可以通过添加以下内容来编辑 showNext 和 showPrev 函数:

// add to showNext()
if (next.next().length===0) {
    stopGallery();
    nextBtn.addClass("hidden");
}

// add to showPrev()
if (prev.prev().length===0) {
    prevBtn.addClass("hidden"); 
}

关于javascript - 使 jQuery 图像 slider 停在最后一张图像并添加下一个和上一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490588/

相关文章:

javascript - 数字 = parseInt(数字);需要从 rel 属性中获取非数字

html - 从 Bootstrap .nav-tabs 中删除一些边框

javascript - Angularjs 使用 API 集成到 django 项目中

javascript - Ajax 发帖速度很慢

javascript - Flask 文件未在 Javascript 提取时更新

javascript - 在 javascript 中使用 .css() 设置细边框

javascript - JQuery 中滚动到 div 时添加类,滚动到另一个 div 时删除类

html - 如何让fa图标显示在菜单中(无字)

javascript - 通过表单发送json对象c# mvc

javascript - 这两者是否相同,或者其中一个比另一个更好/更安全?