【问题标题】:jQuery Draggable Containment Overflow Hidden隐藏的 jQuery 可拖动包含溢出
【发布时间】:2016-05-25 12:01:24
【问题描述】:

这是关于拖动比其父元素更宽的元素(溢出:隐藏)。父级的宽度和溢出选项是固定的,不能更改。

HTML

<div class="container">
  <p class="text">The quick brown fox jumps over the lazy dog.</p>
</div>

CSS

.container {
  position:relative;
  width:300px;
  height:50px;
  background:#ccc;
  overflow:hidden; // be careful, changing to overflow-x:hidden breaks the answer
}
.text {
  position:absolute;
  top:7px;
  margin:0;
  width:1000px;
  font-size:30px;
}

jQuery

$('.text').draggable({
  axis: 'x',
})

修改此演示: https://jsfiddle.net/jeafgilbert/LtkkzccL/

这样我们只能拖动句子句子前后不留空格

【问题讨论】:

    标签: javascript jquery css jquery-ui draggable


    【解决方案1】:

    您可以在drag回调中检查可拖动元素的当前位置,如果超出范围则覆盖该位置。

    换句话说,如果左侧定位大于0,则覆盖左侧定位并将其设置回0,使其永远不会超过0。如果可拖动元素的宽度减去父元素的宽度小于左定位,则覆盖左定位,将其设置回偏移宽度。

    Updated Example

    $('.text').draggable({
      axis: 'x',
      drag: function(event, ui) {
        var left = ui.position.left,
            offsetWidth = ($(this).width() - $(this).parent().width()) * -1;
    
        if (left > 0) {
          ui.position.left = 0;
        }
        if (offsetWidth > left) {
          ui.position.left = offsetWidth;
        }
      }
    });
    .container {
      position: relative;
      width: 300px;
      height: 50px;
      background: #ccc;
      overflow: hidden;
    }
    .text {
      position: absolute;
      top: 7px;
      margin: 0;
      white-space: nowrap;
      font-size: 30px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <div class="container">
      <p class="text">The quick brown fox jumps over the lazy dog.</p>
    </div>

    【讨论】:

    • 谢谢你,乔什·克罗泽!
    • 顺便说一句,强制向右拖动文本会使文本跳到末尾。我添加了父母的宽度以便更容易看到 (jsfiddle.net/jeafgilbert/vom7tpo9/1)。
    猜你喜欢
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多