简体   繁体   中英

jQuery Draggable Containment Overflow Hidden

This is about dragging wider element than its parent (overflow: hidden). Parent's width and overflow options are fixed, cannot be changed.

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',
})

Modify this demo: https://jsfiddle.net/jeafgilbert/LtkkzccL/

So that we can only drag the sentence without making spaces before or after the sentence .

You can check the current position of draggable element in the drag callback and then override the position if it is outside of the bounds.

In other words, if the left positioning is greater than 0 , override the left positioning and set it back to 0 so that it can never exceed 0 . If the width of the draggable element minus the width of the parent element is less than the left positioning, override the left positioning to set it back to the offset width.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM