Jquery splitter在cookie中保存位置

时间:2012-05-02 14:07:56

标签: jquery cookies

我的两个div之间有一个分离器,我能够移动分离器并改变两个容器的大小。我想要做的是保存分割器的位置,缓存中两个容器的宽度,并在刷新浏览器时我希望能够保留那些宽度和位置。这是代码片段,

var separatorPos = $('.content-columns-sep').position().left;           
var leftColumnWidth = $('.content-left').width();
var rightColumnWidth = $('.content-right').width();
if ($.cookie('columnPos')) {
    var cookieVars = $.cookie('columnPos').split(',');           
    var newPos = cookieVars[0];
    var newWidth = cookieVars[1];
    var newRightWidth = cookieVars[2];
    var posDiff = newPos - separatorPos;
    $('.content-columns-sep').offset({
        left: newPos});            
        separatorPos = newPos;
        $('.content-left').width(newWidth);
        $('.content-right').width(newRightWidth);
        leftColumnWidth = newWidth;        
        rightColumnWidth = newRightWidth;        
}            
$( ".content-columns-sep" ).mouseover(function(){
    $('.content-columns-sep').css('cursor', 'crosshair');
});
$( ".content-columns-sep" ).draggable({
    axis: "x",
    containment: "parent",
    cursor: "crosshair",
    grid: [10, 0],
    drag: function(event, ui) {
        var newPos = $('.content-columns-sep').position().left;
        var posDiff = newPos - separatorPos;
        separatorPos = newPos;
        var newWidth = leftColumnWidth + posDiff ;
        var newRightWidth = rightColumnWidth - posDiff;
        $('.content-left').width(newWidth);
        $('.content-right').width(newRightWidth);
        leftColumnWidth = newWidth;        
        rightColumnWidth = newRightWidth;
    },
    stop: function(event, ui) {
        var newPos = $('.content-columns-sep').position().left;
        var posDiff = newPos - separatorPos;
        separatorPos = newPos;
        var newWidth = leftColumnWidth + posDiff ;
        var newRightWidth = rightColumnWidth - posDiff;
        $('.content-left').width(newWidth);
        $('.content-right').width(newRightWidth);
        leftColumnWidth = newWidth;        
        rightColumnWidth = newRightWidth;
        $.cookie('columnPos', separatorPos+','+newWidth+','+newRightWidth);
    }
});     

       But I am unable to get the result as expected, splitter always overlaps one of the div by some 35 pixel or so, what could be the possible reasons ?

1 个答案:

答案 0 :(得分:0)

你的位置是

$('.content-columns-sep').position().left;

但您正在使用该值将其设置为:

$('.content-columns-sep').offset({ left: newPos});     

这可能是你重叠的原因吗?偏移量与位置不同。

当您设置offset时,您正在设置元素相对于整个文档的位置,但是当您获得position时,您将获得相对于偏移父项的位置,这可能是文件,但不一定是。

要么是好的,只要你在整个代码中使用相同的东西。