可水平拖动的图库中 'container' 元素的问题

Issues with 'container' element on a horizontally draggable image gallery

我正在尝试制作一个通过水平拖动来导航的图片库。我目前面临的问题是当元素停止拖动时左右没有边界。我试过使用 'container' 元素,但是当我这样做时,它会完全停止拖动。

我试过使用 'parent' 或实际的 div 作为容器,但都没有正常工作。我在另一个留言板上看到,在这种情况下使用 flexbox 会使事情变得更加复杂,所以我转而使用 display: inline-block on images。

这是我目前的草稿:https://jsfiddle.net/samseurynck/ka1e9soj/21/

HTML

<div class="item_block_left">
  <div class="item_block_left_gallery_container">
    <div class="item_block_left_gallery">
        <img class="item_block_left_gallery_item" src="https://placeimg.com/640/480/animals">
        <img class="item_block_left_gallery_item" src="https://placeimg.com/200/200/animals">
        <img class="item_block_left_gallery_item" src="https://placeimg.com/640/400/animals">
    </div>
  </div>
</div>

SCSS

.item_block_left{
  height:200px; 
  width: 50%;
  border: 1px solid pink;
  overflow: hidden;
  .item_block_left_gallery_container{
    position: relative;
    height:100%;
    width: auto;
    .item_block_left_gallery{
      height:100%;
      display: flex;
      cursor: grab;
      .item_block_left_gallery_item{
        position: relative;
        height:100%;
        width:auto;
        display: inline-block;
      }
    }
  }
}

JQUERY

    $(".item_block_left_gallery").draggable({
      scroll: false,
      axis: "x",
  });

预期的结果是图像只能水平 scroll/drag,左侧或右侧没有白色 space。

工作示例:https://jsfiddle.net/Twisty/4ak6q0zu/44/

JavaScript

$(function() {
  var bounds = {
    left: $(".item_block_left_gallery").position().left
  };
  bounds.right = bounds.left - $(".item_block_left_gallery").width() - $(".item_block_left").width() + 10;

  $(".item_block_left_gallery").draggable({
    scroll: false,
    axis: "x",
    drag: function(e, ui) {
      var l = ui.position.left;
      if (l > bounds.left) {
        console.log("Hit Left Boundry");
        ui.position.left = bounds.left;
      }
      if (l <= bounds.right) {
        console.log("Hit Right Boundry");
        ui.position.left = bounds.right;
      }
    }
  });
});

使用drag回调,您可以检查和设置可拖动项的position。基于拖动项的左边缘,我们可以根据某些特定边界检查和限制移动。右边似乎有一个 10px 的填充或边距,可能只是白色 space,所以我只是调整以纠正这个问题。

查看更多:http://api.jqueryui.com/draggable/#event-drag

希望对您有所帮助。