Remember position and size in a cookie
I have no idea what is to do. Please help.
I have built a website with draggable scaleable items on a page. You can see what I've done here... http://www.hagueandhague.co.uk/test/hagueandhague/httpdocs/index.html
It uses java script from... http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js
What I need the si开发者_如何学JAVAte to do is remember the position and scale of the items so that when visitors return to the site the items are where they left them.
I believe it is possible to store this information in a cookie, however I have no idea how to do that or make it work.
Any help would be great, but even better if it's in english/layman's.
Thanks in advance.
James.
In "layman" terms, you want to use the Draggable plugin's stop
callback to get the position of the element and save it to a cookie using the jQuery cookie plugin. Then when the user returns, read the cookie and re-position the elements.
$(".selector").draggable({
stop: function(event, ui) {
$.cookie("elementIDCookie", ui.position);
}
});
To re-position the element when the user returns:
$(".select").css( { "left" : $.cookie("elementIDCookie").left, "top" : $.cookie("elementIDCookie").top });
More info:
http://jqueryui.com/demos/draggable/
https://github.com/carhartl/jquery-cookie
<script>
$(document).ready(function(){
$('.dragboard').draggable({
stop: function(event, ui) {
$.cookie('elementLeft', ui.position.left);
$.cookie('elementTop', ui.position.top);
}
});
$('.dragboard').css({left : parseInt($.cookie('elementLeft')), top : parseInt($.cookie('elementTop'))});
});
</script>
This will work straight out of the box - #pick-right being the div to drag.
$(document).ready(function () {
if ($.cookie("rcpos") != undefined) {
var unwrapped = window.JSON.parse($.cookie("rcpos"));
var left = window.JSON.parse($.cookie("rcpos")).left;
var top = window.JSON.parse($.cookie("rcpos")).top;
$("#pick-right").css("left", left + "px");
$("#pick-right").css("top", top + "px");
}
});
$(function () {
$("#pick-right").draggable({ stop: function (event, ui) {
$.cookie("rcpos", window.JSON.stringify(ui.position));
}
});
});
精彩评论