在浏览器调整大小时保持div在视图中



我正在做一个像桌面一样的网站,用户可以在屏幕上拖动图标,然后点击它们打开窗口。我遇到的问题是保持图标始终在视图中,这样如果用户减小浏览器大小,图标就不会消失在右边。本网站通过看似"翻译"的方式实现了这一目标。但我不知道怎么做?

到目前为止,我所实现的是通过使用%设置图标的位置来保持图标在视图中。但是一旦图标被拖动,这个位置就不再适用了,如果你调整浏览器的大小,图标就会停留在你离开它的地方,并从屏幕上消失。

请参阅下面的示例,加载代码片段并全屏查看,然后调整浏览器大小,文本始终保持在视图中。但是,一旦你移动了文本,然后调整了浏览器的大小,它就会保持在原来的位置,而不是随着浏览器移动。

$(function() {
$(".drag-me").draggable();
});
.drag-me {
font-family: 'Lato', sans-serif;
font-weight: 300;
font-size: 16px;
line-height: 16px;
position: absolute;
cursor: pointer;
top: 20% ;
left: 50% ;
width:50px;
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div class="drag-me">
<span>Drag me around!</span>
</div>

您可以使用"containment: "window"选项和辅助函数。

$(function() {
$(".drag-me").draggable({
containment: "window",
stop: function(e, ui) {
var perc = ui.position.left / ui.helper.parent().width() * 100;
ui.helper.css('left', perc + '%');
}
});
});
.drag-me {
font-family: 'Lato', sans-serif;
font-weight: 300;
font-size: 16px;
line-height: 16px;
position: absolute;
cursor: pointer;
top: 20% ;
left: 50% ;
width:50px;
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div class="drag-me">
<span>Drag me around!</span>
</div>

最新更新