我有一个固定 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>
最佳答案
一个简单的解决方案是使用固定位置的叠加层/包装器:
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
});
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;
}
<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>
关于以百分比设置位置,可以查看this answer .
关于javascript - 元素离开屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078072/