我一直在尝试制作一个jquery可拖动文本框并且它工作成功,现在我试图让文本框记住其最后位置的坐标。我已经从高处和低处寻找过。我找到了一些例子,但它们从未起作用。因此,当我将文本框放置在页面上的某个位置并刷新页面时,我希望它位于上次所在的位置。下面我将向您提供的代码是每次刷新时都会返回到的代码原来的位置。有人可以帮忙吗?
这是代码。
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Something</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#draggable { width: 75px; height: 50px; padding: 0.25em; }
</style>
<script>
$(function() {
$('#draggable').draggable(
{
drag: function(){
var offset = $(this).offset();
var xPos = offset.left;
var yPos = offset.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
}
});
});
</script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#test { width: 75px; height: 50px; padding: 0.25em; }
</style>
<script>
$(function() {
$( "#test" ).draggable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>Test</p>
</div>
<div id="test" class="ui-widget-content">
<p>Test</p>
</div>
</body>
</html>
感谢您的帮助!
最佳答案
如果您使用浏览器 (F5) 刷新页面,则无法在不将位置保存在某处( session 、数据库、cookie、本地存储等)的情况下恢复 elemente 的位置,因为页面已完全重新加载。
例如,您可以简单地使用 jquery.cookie
用于设置/获取包含拖动的 div 位置的 cookie 的插件:
$('#draggable').draggable({
drag: function () {
var cookie_value = JSON.stringify($(this).offset());
$.cookie('newPosition', cookie_value, {
expires: 7
});
}
});
if ($.cookie('newPosition')) {
//console.log($.cookie('newPosition'))
$("#draggable").offset({
top: JSON.parse($.cookie('newPosition')).top,
left: JSON.parse($.cookie('newPosition')).left
})
}
或调用 get/set webmethods 来使用 jQuery.ajax 处理位置
这是一个使用 cookies 的工作 fiddle :http://jsfiddle.net/IrvinDominin/pqhQu/
关于jquery - 使用 Jquery 可拖动框保持位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16579156/