无法获取表单's面板的x和y坐标,并在加载时从cookie中设置它们

Unable to get form's panel x and y coordinates and to set them from a cookie on load

本文关键字:加载 坐标 设置 cookie 表单 获取      更新时间:2023-09-26

我有一个表单,里面有一个面板:

<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中的属性进行定位和对齐。我面临的第一个问题是,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方法。