我有一个内部带有面板的表单:

<form id="form" action="/accent/login/enter/">
    <div draggable="true" id="panel" title="">
    ...


面板是draggableresizable,并且有两个事件:

$('#panel').bind("resize",function(event){
               saveform();
           })
           .bind("drag",function(event){
               saveform();
           });


函数saveform应该保存表单的面板widthheight,并保存x和y坐标。它将其保存在cookie中。我想要这种行为,以便用户刷新页面时,将根据保存在cookie中的那些属性来定位和对齐表单的面板。我面临的第一个问题是x和y坐标仅重新计算一次,即用户第一次拖放表单时。至于高度和宽度,它们会重新正确计算。我面临的第二个问题是我无法设置表单的x和y坐标-我不知道我使用的方法是否合适。因此,我的saveform函数如下所示:

var saveform = function(){
    var pos = $('#form:first').offset(), // recalculated only once
    height = $('#panel').height(), // it is saved ok
    width = $('#panel').width(), // it's ok too
    data = {top:Math.round(pos.top),left:Math.round(pos.left),
        height:Math.round(height),width:Math.round(width)};
    $.cookie('form',data);
}


这是我用来设置面板的x和y坐标的方法:

var data = $.cookie('form');
$('#panel').position({
        of:$('#body'),
        my:'left top',
        at:'left top',
        offset:data.left + " " + data.top
})

最佳答案

好吧,我找到了解决方案。现在,我的saveform函数如下所示:

var saveform = function(){
    var pos = $('div.panel').offset(), //I added class="panel" to main div
    height = $('#panel').height(),
    width = $('#panel').width();
    $.cookie('form',{top:pos.top,left:pos.left,
        height:height,width:width});
}


然后将面板的x和y设置为如下所示:

var data = $.cookie('form');
$('#panel').height(data.height).width(data.width)
               .offset({top:data.top,left:data.left});


因此,主要技巧是以适当的方式应用offset方法。

关于javascript - 无法获取表单的面板x和y坐标,也无法从加载时的cookie中进行设置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29181616/

10-17 02:56