如何保存可拖动和可调整大小元素的位置?

问题描述 投票:4回答:2

我正在构建一个网站,允许用户创建一个html页面,然后可以在另一个站点上保存和共享。我希望他们能够调整大小并拖动页面元素。我可以使用jQuery做到这一点,但我不知道如何保存它,以便在其他地方查看页面时,它看起来是一样的。

我还没有决定如何存储页面信息,但我在想的是我可以将每个元素与其绝对位置及其内容一起存储在数据库中。这听起来像个好计划吗?

如果是这样,我如何获得div的位置传递给php,以便它可以保存?

谢谢。

jquery-ui jquery-ui-resizable jquery-ui-draggable
2个回答
13
投票

JQueryUI Resizable有一个名为resize的事件,您可以使用:

var resposition = '';

$('#divresize').resizable({
   //options...
   resize: function(event,ui){
      resposition = ui.position;
   }
});

JQueryUI Draggable及其事件drag也是如此:

var dragposition = '';

$('#divdrag').draggable({
   // other options...
   drag: function(event,ui){
      dragposition = ui.position;
   }
});

respositiondragposition将成为阵列。你可以看到它在这里工作:http://jsbin.com/uvuzi5

编辑:使用表单,您可以将dragpositionresposition保存到隐藏的输入中

var inputres = '<input type="hidden" id="resposition" value="'+resposition.left+','+resposition.top+'"/>'
$('#myform').append(inputres);
var inputdrag = '<input type="hidden" id="dragposition" value="'+dragposition.left+','+dragposition.top+'"/>'
$('#myform').append(inputdrag);

并在您的PHP文件中处理表单:

$dragposition = $_GET['dragposition'];
$resposition = $_GET['resposition'];
$dragposition = explode(',',$dragposition);
$resposition = explode(',',$resposition);

最后,两个变量都应该是具有top和left属性的数组:

$dragposition => [top,left] attributes from draggable
$resposition => [top,left] attributes from resizable

0
投票

你必须在某些地方保存位置,以便下次打开页面时可以获得位置详细信息。

选项1:您可以将“localStorage”中的html元素位置详细信息存储为其默认浏览器存储。 Example: Demo

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Dashboard</title>
    <!-- jQuery -->
    <script src="vendor/jquery/jquery.min.js"></script>

    <link rel="stylesheet" type="text/css" href="dist/css/jquery-ui.min.css">
    <script src="dist/js/jquery-ui.min.js"></script>
</head>

<body>
    <script>
        var positions = JSON.parse(localStorage.positions || "{}");
        $(function() {
            var d = $("[id=draggable]").attr("id", function(i) {
                return "draggable_" + i
            })
            $.each(positions, function(id, pos) {
                $("#" + id).css(pos)
            })

            d.draggable({
                containment: "#wrapper",
                scroll: false,
                stop: function(event, ui) {
                    positions[this.id] = ui.position
                    localStorage.positions = JSON.stringify(positions)
                }
            });
        });
    </script>
    <div id="wrapper">
        <div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div1</div>
        <div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div2</div>
        <div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div3</div>
    </div>
</body>

</html>

选项2:您可以在“您的数据库”中存储html元素位置详细信息

© www.soinside.com 2019 - 2024. All rights reserved.