首页 > 解决方案 > 水平可拖动图像库上的“容器”元素问题

问题描述

我正在尝试制作一个通过水平拖动进行导航的图片库。我目前面临的问题是元素应该停止拖动时左右没有界限。我尝试过使用“容器”元素,但是当我这样做时,它会完全停止拖动。

我尝试过使用“父级”或实际的 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;
      }
    }
  }
}

查询

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

预期的结果是只能水平滚动/拖动图像,左侧或右侧没有空白。

标签: jquery-uiresponsive-designflexboxdraggableimage-gallery

解决方案


工作示例: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 的填充或边距,可能只是空白,所以我只是对此进行了调整。

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

希望有帮助。


推荐阅读