jQuery可移动的遏制溢出隐藏

Jea*_*ert 6 javascript css jquery jquery-ui draggable

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

HTML

<div class="container">
  <p class="text">The quick brown fox jumps over the lazy dog.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

jQuery的

$('.text').draggable({
  axis: 'x',
})
Run Code Online (Sandbox Code Playgroud)

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

因此,我们只能拖动句子而不在句子之前或之后创建空格.

Jos*_*ier 4

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

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

更新的示例

$('.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;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
.container {
  position: relative;
  width: 300px;
  height: 50px;
  background: #ccc;
  overflow: hidden;
}
.text {
  position: absolute;
  top: 7px;
  margin: 0;
  white-space: nowrap;
  font-size: 30px;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)