2011-06-06 34 views
2

嘿傢伙, 我似乎無法得到它的工作。我有可拖動的黑條,充當導航內容的頂部。jQuery:可拖動的酒吧 - 記得與cookie的位置?

我只是想瀏覽器記住用cookie的酒吧的位置。只要用戶拖動欄並單擊其他內容(頁面刷新),欄就應該停留在最後的位置。

我似乎無法得到它的工作。此外,我希望當用戶第一次訪問該網站時,可以隨意分發酒吧。

我已經構建了一個快速示例。也許你知道我在做什麼錯在這裏:http://jsfiddle.net/RZQ8H/

$("ul.bars li").draggable({ 
    stop: function(event, ui) { 
     var currentPos = $(this).position(); 
     var currentTop = Math.round(currentPos.top); 

     // save cookie when stopped dragging 
     $.cookie('position' + $(this).index('li').toString(), currentTop.toString()); 
    } 
}); 

位置時,頁面加載...

// initial position of elements 
$("ul.bars li").each(function() { 

     // if no cookie is set (first visit to page) all bars should be distributed 
     // randomly across the document 

     if ($.cookie('position'+ $(this).index('li').toString())) { 
      var doc = $(document).height() - 50; 

      // random distribution of elements 
      $("ul.bars li").each(function() { 
       var randPos = Math.random(0)*doc; 
       $(this).css('top' , randPos+'px'); 
      }); 

     } else { 

      // if a cookie exists (the bars have already been dragged) 
      // remember the position 

      var savedPos = $.cookie('position' + $(this).index('li').toString());    

      $(this).css({ top: savedPos + 'px' }); 
     } 

}); 
+0

該Cookie插件不從的jsfiddle – Niklas 2011-06-06 11:22:06

+0

所應用的資源加載哪些你沒有提到的是,你[使用jQuery插件(HTTP:// plugins.jquery.com/project/Cookie)。 – 2011-06-06 11:23:10

回答

0

你有你的條件不對辦法解決:

if ($.cookie('position'+ $(this).index('li').toString())) { 

      // random distribution of elements 


     } else { 

      // if a cookie exists (the bars have already been dragged) 
      // remember the position 

     } 

交換它,這樣如果一個cookie存在,它不會隨機分配它們。

if (!$.cookie('position'+ $(this).index('li').toString())) { 

例子: http://fiddle.jshell.net/RZQ8H/3/show/

+0

謝謝你,但測試你的例子與多個重新加載。東西是越野車。它並不記得元素的每個位置。這是我的問題。我只是想拖動一個欄(然後點擊或重新加載),欄不會移動它的位置。 – matt 2011-06-06 11:39:30

+0

@mathiregister這是因爲您在保存cookie之前重新加載了頁面。嘗試移動一個元素,放下它,然後等待10秒鐘。它肯定應該保存在重新加載。 – Niklas 2011-06-06 11:46:06

+0

謝謝,但不適合我。可以等一個小時。我從瀏覽器中刪除了所有的cookies,然後再次嘗試。沒有機會。首先,酒吧不會隨機分佈,並且會出現一些錯誤(有些不會顯示)...並且在拖動(等待)並重新加載或單擊鏈接時,酒吧的位置會發生變化。沒有辦法讓這個簡單的工作。無縫withoug 10秒。普通用戶永遠不會等待10秒,對。 – matt 2011-06-06 12:04:39