简体   繁体   English

将 div 的内联样式保存到 cookie 不起作用

[英]Saving inline styles of a div to cookie doesn't work

I have a problem with this html page.我有这个 html 页面的问题。 The position of the box should be saved in the cookie, but only the top: attribute is saved instead of top and left.盒子的位置应该保存在cookie中,但是只保存top:属性而不是top和left。 在此处输入图片说明 is saved instead of被保存而不是

在此处输入图片说明

 function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } //Make the DIV element draggagle: document.getElementById("mydiv").setAttribute("style",getCookie("a")); dragElement(document.getElementById(("mydiv"))); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementById(elmnt.id + "header")) { /* if present, the header is where you move the DIV from:*/ document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; } else { /* otherwise, move the DIV from anywhere inside the DIV:*/ elmnt.onmousedown = dragMouseDown; } function dragMouseDown(e) { e = e || window.event; // get the mouse cursor position at startup: pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; // calculate the new cursor position: pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } function closeDragElement() { setCookie("a",document.getElementById("mydiv").style.cssText,1); /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } }
 #mydiv { position: absolute; z-index: 9; background-color: #f1f1f1; text-align: center; border: 1px solid #d3d3d3; } #mydivheader { padding: 10px; cursor: move; z-index: 10; background-color: #2196F3; color: #fff; }
 <!DOCTYPE html> <html> <body> <div id="mydiv" > <div id="mydivheader">Title</div> <div contenteditable="true"> <p>Move gfsdg gt gf gfg g fdgdfgfdg</p> </div> </div> </body> </html>

I am trying to put in the cookie "a" the value of the attribute "style" when box drag ends.当框拖动结束时,我试图将属性“style”的值放入cookie“a”中。

I would prefer a non-jquery answer.我更喜欢非 jquery 答案。

Thanks.谢谢。

Note: I agree with Nisarg's answer, using localStorage is a lot easier than cookies, so you should consider using that instead.注意:我同意 Nisarg 的回答,使用localStorage比使用 cookie 容易得多,因此您应该考虑改用它。

Semi colons are not allowed in cookie names or values. cookie 名称或值中不允许使用分号。 They have a meaning, and are used to separate parameters.它们有含义,用于分隔参数。

You need to replace them with something else, like this for example:您需要用其他东西替换它们,例如:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    // Replace semicolons before saving the cookie
    var escapedCvalue = cvalue.replace(/;/g, '{{semicolon}}');  // <-------
    document.cookie = cname + "=" + escapedCvalue + ";" + expires + ";path=/"; // <-------
}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie .split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length)
                    // Put semicolons back in there
                    .replace(/\{\{semicolon\}\}/g, ';'); // <------
        }
    }
    return "";
}

The answer from Blex already points out the problem with the semicolons going into the cookie value, so I won't repeat that. Blex 的回答已经指出分号进入 cookie 值的问题,所以我不会重复。

The other alternative is to use localStorage instead of cookie.另一种选择是使用localStorage而不是 cookie。 It doesn't come with the limitation against semicolons, and a major benefit of using localStorage in this instance would be that it won't be sent to the server with every HTTP request.它没有对分号的限制,在这种情况下使用 localStorage 的一个主要好处是它不会随每个 HTTP 请求发送到服务器。

Here's how your code looks if you simply changed the storage from cookie to localStorage:如果您只是将存储从 cookie 更改为 localStorage,您的代码如下所示:

function setCookie(cname, cvalue, exdays) {
    localStorage.setItem(cname, cvalue);
}
function getCookie(cname) {
    return localStorage.getItem(cname);
}

Of course, you'd want to change the function name from setCookie and getCookie to something generic like persistConfiguration and loadConfiguation .当然,你会希望函数名从改变setCookiegetCookie的东西一般像persistConfigurationloadConfiguation

You can see working example here: https://codepen.io/Nisargshah02/pen/Ovebqz?editors=0010您可以在此处查看工作示例: https : //codepen.io/Nisargshah02/pen/Ovebqz?editors=0010


You can read more about differences between localStorage and cookies here: Local Storage vs Cookies您可以在此处阅读有关 localStorage 和 cookie 之间差异的更多信息: Local Storage vs Cookies

Here's MDN's documentations about localStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage这是 MDN 关于 localStorage 的文档: https : //developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM