首页 > 解决方案 > 如何在 CSS 轮播中添加“下一张幻灯片”按钮,同时保持原生滚动?

问题描述

我制作了一个简单的水平轮播,并想添加一个按钮来“跳转到”每个图像/卡片。我很接近一些jquery。

HTML:

<div class="wrap">
<div class="p p1 active"></div>
<div class="p p2"></div>
<div class="p p3"></div>
</div>
<button class="next">NEXT</button>

CSS:

.wrap {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  position: relative;
  width: 100%;
}
.p {
    flex: 0 0 auto;
    width: 100%;
    height: 80px;
}

查询:

$(".next").click(function() {
  var $target = $('.p.active').next('.p');
  if ($target.length == 0)
    $target = $('.p:first');

  $('.wrap').animate({
    scrollLeft: $target.offset().left
  }, 'slow');

  $('.active').removeClass('active');
  $target.addClass('active');
});

https://codepen.io/drewbots/pen/eYJzQQX

为了简单起见,我喜欢 vanilla Javascript,但工作 jquery 会很好。在此先感谢您的帮助!

标签: javascripthtmljquerycss

解决方案


使用 offset 方法获取元素相对于文档的位置并滚动到元素使用 animate 与 scrollLeft 和 scrollTop



$(".next").click(function() {
  let offset
  let active = $('.active')
  let target = active.next()
  if(active.next()[0] == undefined) 
    target = $('.p').first()
    
  offset = target.offset()
  
  $('.wrap').animate({
      scrollLeft: $('.wrap').scrollLeft() + offset.left,
      scrollTop: $('.wrap').scrollTop() + offset.top
    })
  
  target.addClass('active')
  active.removeClass('active')
   
})
body {
  margin:0;
}
.wrap {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  position: relative;
  width: 100%;
}
.p {
    flex: 0 0 auto;
    width: 100%;
    height: 80px;
}
.p1 {
  background-color: #2196F3;
}
.p2 {
  background-color: #E91E63;
}
.p3 {
  background-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<div class="p p1 active"></div>
<div class="p p2"></div>
<div class="p p3"></div>
</div>
  <button class="next">NEXT</button>


推荐阅读