【问题标题】:jQuery: draggable bars - remember position with cookie?jQuery:可拖动条 - 还记得 cookie 的位置吗?
【发布时间】:2011-06-06 11:15:16
【问题描述】:

大家好, 我似乎无法让它工作。我有可拖动的黑条作为内容顶部的导航。

我只是想让浏览器记住带有 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' });
        }

});

【问题讨论】:

标签: jquery jquery-ui cookies drag-and-drop draggable


【解决方案1】:

你的病情搞错了:

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/

【讨论】:

  • 谢谢你,但是用多次重新加载来测试你的例子。事情是错误的。它并不真正记住元素的每个位置。那是我的问题。我只是想拖动一个栏(然后单击或重新加载)并且该栏不会移动它的位置。
  • @mathiregister 那是因为您在保存 cookie 之前重新加载页面。尝试移动一个元素,放下它,然后等待 10 秒。它肯定应该在重新加载时保存。
  • 谢谢,但对我不起作用。可以等一个小时。我已从浏览器中删除所有 cookie 并再次尝试。没有机会。首先,条形图永远不会在没有错误的情况下随机分布(有些不会出现)......当拖动(等待)并重新加载或单击链接时,条形图的位置会发生变化。有没有办法让它简单地工作。无需 10 秒即可无缝。普通用户永远不会等待 10 秒,对吧。
  • 我很难开始对您的案例进行故障排除,因为从我的角度来看它工作正常。您是否检查过您是否收到了 cookie?
  • 好的,这很奇怪,它在你的例子中也对我有用。然而,在我的网站上,这可能不是因为 wordpress 或其他原因?自己看吧。 bit.ly/jEAwVh
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
相关资源
最近更新 更多