2012-05-02 51 views
1

我在兩個div之間有一個分離器,我可以移動分離器並更改兩個容器的大小。我想要做的是保存分離器的位置,兩個容器在緩存中的寬度以及刷新瀏覽器時我希望能夠保留這些寬度和位置。這裏的代碼片段,jquery splitter在cookie中保存位置

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 ? 
+0

你已經在你粘貼的代碼中使用了cookie,是代碼不工作,還是你想擴展它?你可以提供一個[JsFiddle](http://www.jsfiddle.net),代碼在某些標記的上下文中運行,以便我們可以看看可能出現的問題? –

+0

當然我正在研究它 –

回答

0

你得到的位置

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

但是,你正在使用的值設置爲:

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

也許這是你重疊的原因是什麼?偏移與位置不一樣。

當您設置offset時,您將設置元素相對於整個文檔的位置,但是當您獲取position時,您會得到它相對於可以是文檔的偏移父項的相對位置,但是不一定是。

或者應該沒問題,只要你在整個代碼中使用相同。

+0

我曾嘗試過,但沒有奏效 –