首页 > 解决方案 > 如何在jQuery中创建左右按钮来移动产品轮播?

问题描述

调查并一点一点地整理我的代码,我已经实现了一个带有 mouseup 功能的轮播,它允许我通过按下鼠标左键而不释放它来移动产品,到目前为止它运行得很好,有时它仍然存在停滞不前,也就是说,如果我移动指针,则无需按下即可移动产品。

我想在我的代码中实现的是能够集成两个按钮,一个右一个左一个,也能够以这种方式移动轮播的产品。我怎样才能实现它,你能给我解释一下吗?

    var direction_slider = "up";
    var current_step = 0;
    var scroll_product = false;
    var scroll = -1;

$(function(){
    // vars for clients list carousel 
    var $product_carousel = $('.slider');
    var products = $product_carousel.children().length;
    var product_width = (products * 140); // 140px width for each client item 
    $product_carousel.css('width',product_width);

    var rotating = true;
    //var product_speed = 1800;
    //var see_products = setInterval(rotateClients, product_speed);

    $(document).on({
        mouseenter: function(){
            rotating = false; // turn off rotation when hovering
        },
        mouseleave: function(){
            rotating = true;
        }
    }, '#carousel');

    $product_carousel.on("mousedown", function(e) {
        scroll_product = true;
        scroll = e.pageX;
        event.preventDefault();
    }).on("mouseup", function(e) {
        scroll_product = false;
        var num = Math.floor(Math.abs(scroll - e.pageX) / 140);
        var dir = scroll - e.pageX < 0 ? "up" : "down";
        for (var x = 0; x < num; x++) {
            var $first = $('.slider .item:first');
            var $last  = $('.slider .item:last');
            if (dir == "up") {
                $last.prependTo(".slider");
            } else {
                $first.appendTo(".slider");
            }
        }
        $(".slider").css("transform", "translate(0, 0)")
    }).on("mousemove", function(e) {
        if (scroll_product) {
            $(".slider").css("transform", "translate(" + ( e.pageX - scroll ) +"px, 0)")
        }
    });
});
.carousel {
    margin: 0 auto;
    padding: 1em;
    width: 100%;
    max-width: 1170px;
    margin-left: auto;
    overflow: hidden;
}
.slider {
    width: 100% !important;
    display: flex;
}
.item {
    display: inline-table;
    width: 280px;
    height: 325px;
    margin: 0.5em;
    border: 1px solid #ccc;
}
a {
    color: #8563CF;
    text-decoration: none;
    font-weight: 100;
}
.thumbnail {
    height: 150px;
    position: relative;
}
.thumbnail img {
    height: 100%;
    width: 100%;
    object-fit: cover;
    object-position: 50% 15%;
}

img {
    border: 0;
    height: auto;
    max-width: 100%;
    vertical-align: middle;
}
.p1em {
    padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="carousel">
                                        <div id="carousel">
                                            <div class="slider" style="width: 280px; transform: translate(0px, 0px);">
                                                    <div class="item product">
        <a href="#">
            <div class="thumbnail image">
                <img src="https://i.ytimg.com/vi/ZxrUVuOqsy0/maxresdefault.jpg">
            </div>
            <div class="box p1em">
                <div class="heading ellipsis">
                    <h3>Prueba 1</h3>
                </div>
                <div class="author">
                    <span></span>
                </div>
                                <div class="price right">
                    <p>
                        <label></label>
                        <em class="item-price">$40.130,00</em>
                    </p>
                </div>
                            </div>
        </a>
    </div>  <div class="item product">
        <a href="#">
            <div class="thumbnail image">
                <img src="https://i.ytimg.com/vi/ZxrUVuOqsy0/maxresdefault.jpg">
            </div>
            <div class="box p1em">
                <div class="heading ellipsis">
                    <h3>Curso de PHP 8 básico, intermedio y, avanzado. </h3>
                </div>
                <div class="author">
                    <span>Acaded</span>
                </div>
                                <div class="purchased items-center">
                    <button>Ir al curso</button>
                </div>
                            </div>
        </a>
    </div>

                                            </div>
                                        </div>
                                    </div>

标签: htmljquerycss

解决方案


这里的目标是将元素的顺序向左或向右移动。使用 jQuery,这非常容易。

逻辑是这样的:

  • 要将顺序向右移动,请选择最后一项,将其删除,然后在第一项之前插入

  • 要将顺序向左移动,请选择第一项,将其删除,然后在最后一项之后插入

为此,我们将click事件侦听器附加到每个相应的按钮。我们使用选择器选择所有滑块项目$('.item.product'),使用last() andfirst()获取第一个和最后一个项目,以及remove()删除元素的功能。然后,为了重新排序,我们使用 jQueryinsertBefore()insertAfter().

这是结果:

$('#right').click(function() {
    $('.item.product').last().remove().insertBefore($('.item.product').first());
})
$('#left').click(function() {
    $('.item.product').first().remove().insertAfter($('.item.product').last());
})

其余的只是样式问题(注意:使用Material Icons作为箭头图标)。定义两个按钮元素;

<button id="left" class="nav-btn"><i class="material-icons">chevron_left</i></button>
<button id="right" class="nav-btn"><i class="material-icons">chevron_right</i></button>

“chevron_right”和“chevron_left”是图标名称 | 图标列表

将它们的位置设置为固定,这样当用户滚动时它们的位置就不会丢失。将top属性设置为calc(50vh - 50px),其中50vh是视口高度的一半,50px是按钮的高度(使其恰好位于“中心”)。

一个完整的例子(最好在全页模式下查看):

var direction_slider = "up";
var current_step = 0;
var scroll_product = false;
var scroll = -1;

$(function() {
  $('#right').click(function() {
    $('.item.product').last().remove().insertBefore($('.item.product').first());
  })
  $('#left').click(function() {
    $('.item.product').first().remove().insertAfter($('.item.product').last());
  })
  var $product_carousel = $('.slider');
  var products = $product_carousel.children().length;
  var product_width = (products * 140);
  $product_carousel.css('width', product_width);
  var rotating = true;
  $(document).on({
    mouseenter: function() {
      rotating = false;
    },
    mouseleave: function() {
      rotating = true;
    }
  }, '#carousel');

  $product_carousel.on("mousedown", function(e) {
    scroll_product = true;
    scroll = e.pageX;
    event.preventDefault();
  }).on("mouseup", function(e) {
    scroll_product = false;
    var num = Math.floor(Math.abs(scroll - e.pageX) / 140);
    var dir = scroll - e.pageX < 0 ? "up" : "down";
    for (var x = 0; x < num; x++) {
      var $first = $('.slider .item:first');
      var $last = $('.slider .item:last');
      if (dir == "up") {
        $last.prependTo(".slider");
      } else {
        $first.appendTo(".slider");
      }
    }
    $(".slider").css("transform", "translate(0, 0)")
  }).on("mousemove", function(e) {
    if (scroll_product) {
      $(".slider").css("transform", "translate(" + (e.pageX - scroll) + "px, 0)")
    }
  });
});
/* button integration styling (start) */

#left {
  left: 10px;
}

#right {
  right: 10px;
}

.nav-btn {
  position: fixed;
  top: calc(50vh - 50px);
  z-index: 100;
  z-index: 100;
  height: 50px;
  width: 50px;
  border-radius: 50%;
  cursor: pointer;
  background-color: white;
  box-shadow: 0 0 1px black;
  transition: 0.2s;
}

.nav-btn:hover {
  background-color: #d1d1d1;
}


/* button integration styling (end) */

.carousel {
  margin: 0 auto;
  padding: 1em;
  width: 100%;
  max-width: 1170px;
  margin-left: auto;
  overflow: hidden;
}

.slider {
  width: 100% !important;
  display: flex;
}

.item {
  display: inline-table;
  width: 280px;
  height: 325px;
  margin: 0.5em;
  border: 1px solid #ccc;
}

a {
  color: #8563CF;
  text-decoration: none;
  font-weight: 100;
}

.thumbnail {
  height: 150px;
  position: relative;
}

.thumbnail img {
  height: 100%;
  width: 100%;
  object-fit: cover;
  object-position: 50% 15%;
}

img {
  border: 0;
  height: auto;
  max-width: 100%;
  vertical-align: middle;
}

.p1em {
  padding: 1em;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="carousel">
  <button id="left" class="nav-btn"><i class="material-icons">chevron_left</i></button>
  <button id="right" class="nav-btn"><i class="material-icons">chevron_right</i></button>
  <div id="carousel">
    <div class="slider" style="width: 280px; transform: translate(0px, 0px);">
      <div class="item product">
        <a href="#">
          <div class="thumbnail image">
            <img src="https://i.ytimg.com/vi/ZxrUVuOqsy0/maxresdefault.jpg">
          </div>
          <div class="box p1em">
            <div class="heading ellipsis">
              <h3>Prueba 1</h3>
            </div>
            <div class="author">
              <span></span>
            </div>
            <div class="price right">
              <p>
                <label></label>
                <em class="item-price">$40.130,00</em>
              </p>
            </div>
          </div>
        </a>
      </div>
      <div class="item product">
        <a href="#">
          <div class="thumbnail image">
            <img src="https://i.ytimg.com/vi/ZxrUVuOqsy0/maxresdefault.jpg">
          </div>
          <div class="box p1em">
            <div class="heading ellipsis">
              <h3>Curso de PHP 8 básico, intermedio y, avanzado. </h3>
            </div>
            <div class="author">
              <span>Acaded</span>
            </div>
            <div class="purchased items-center">
              <button>Ir al curso</button>
            </div>
          </div>
        </a>
      </div>
      <div class="item product">
        <a href="#">
          <div class="thumbnail image">
            <img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=96&d=identicon&r=PG&f=1">
          </div>
          <div class="box p1em">
            <div class="heading ellipsis">
              <h3>Spectric</h3>
            </div>
            <div class="author">
              <span>Spectric</span>
            </div>
            <div class="purchased items-center">
              <button>Check out</button>
            </div>
          </div>
        </a>
      </div>
    </div>
  </div>
</div>


推荐阅读