元素离开屏幕

时间:2015-12-03 23:14:03

标签: javascript jquery html css jquery-ui

我有一个已修复 div,我通过JQuery UI进行了拖拽。 div以启动为中心。

问题是,当div被拖出屏幕时(意味着,因为它离开了屏幕,页面开始滚动),div会转到一边。拖动的越多,它离光标越远。

另外,我如何定位div百分比,这样当浏览器调整大小时,div将保持其位置? (即使它被拖了之后。)

JSFiddle



var dragDiv = $('#draggable');

dragDiv.css({
  'top': ($(window).height() / 2) - (dragDiv.outerHeight() / 2),
  'left': ($(window).width() / 2) - (dragDiv.outerWidth() / 2)
});

dragDiv.draggable();

body {
  width: 2000px;
  height: 2000px;
  background-image: url("http://www.freevector.com/site_media/preview_images/FreeVector-Square-Patterns-Set.jpg");
}
#draggable {
  color: lightblue;
  background-color: red;
  width: 200px;
  position: fixed;
}

<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>


<div id="draggable">Drag Me!</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案是使用固定位置叠加/包装器:

<强> Working Example

&#13;
&#13;
var dragDiv = $('#draggable');

dragDiv.css({
  'top': ($(window).height() / 2) - (dragDiv.outerHeight() / 2),
  'left': ($(window).width() / 2) - (dragDiv.outerWidth() / 2)
});

dragDiv.draggable({
  containment: "parent" // <- keep draggable within fixed overlay
});
&#13;
body {
  width: 2000px;
  height: 2000px;
  background-image: url("http://www.freevector.com/site_media/preview_images/FreeVector-Square-Patterns-Set.jpg");
}
#fixed {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.25)
}
#draggable {
  color: lightblue;
  background-color: red;
  width: 200px;
  position: absolute;
}
&#13;
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<div id="fixed">fixed overlay<!-- add fixed position overlay/wrapper -->
  <div id="draggable">Drag Me!</div>
</div>
&#13;
&#13;
&#13;

至于以百分比设置位置,您可以查看this answer