doukang7858 2016-06-10 12:30 采纳率: 0%
浏览 75
已采纳

设置Javascript cookie并检索它们

I want to have a DIV that can be dragged around the screen and for the position to be saved so that next time I return, the DIV is in the same place.

I've got the functionality working using javascript / CSS and by storing the position values to a javascript cookie, which is then retrieved when the page is reloaded (code below)

My issue is that i have a single page which the content is loaded on different parts of the screen depending on the variable in the URL is

i.e. www.example.com/example.php?date=10062016 may have content filling the left hand side of the screen and www.example.com/example.php?date=11062016 may have content on the right hand side of the screen. Therefore, if i dragged the DIV to the right hand side of the screen, the content is covered on one page but not for another.

I believe that what i need to do is to save the cookies name as the value of the php variable (the date) and load the cookie with the name that is the variable. I believe that this will allow me to store multiple cookies which will save the different positions for different days.

I have also commented out the javascript that I thought may have worked at the bottom

function drag_start(event) {
    var style = window.getComputedStyle(event.target, null);
    event.dataTransfer.setData("text/plain",
    (parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
} 
function drag_over(event) { 
    event.preventDefault(); 
    return false; 
} 
function drop(event) { 
    var offset = event.dataTransfer.getData("text/plain").split(',');
    var dm = document.getElementById('dragme');
    dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
    dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
    var pos = {left: dm.style.left, top: dm.style.top};
    document.cookie = JSON.stringify(pos);
    event.preventDefault();
    return false;
}
var dm = document.getElementById('dragme'); 
try {
  var pos = JSON.parse(document.cookie);
  dm.style.left = pos.left ? pos.left : '0px';
  dm.style.top = pos.top ? pos.top : '0px';
} catch (e) {
  // Some error handling
}
dm.addEventListener('dragstart',drag_start,false); 
document.body.addEventListener('dragover',drag_over,false); 
document.body.addEventListener('drop',drop,false); 


/*

function drop(event) { 
    var offset = event.dataTransfer.getData("text/plain").split(',');
    var dm = document.getElementById('dragme');
    dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
    dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
    var pos = {left: dm.style.left, top: dm.style.top};
    var str = JSON.stringify(pos);
    var dat = <?php echo $_GET[date];?>;
    document.cookie = dat+"="+str;
    event.preventDefault();
    return false;
}
var dm = document.getElementById('dragme'); 
try {
  var pos = JSON.parse(dat);
  dm.style.left = pos.left ? pos.left : '0px';
  dm.style.top = pos.top ? pos.top : '0px';
} catch (e) {
  // Some error handling
}
*/
aside { 
    position:  absolute;
    left: 0;
    top: 0; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
    width: 200px; 
    background: rgba(255,255,255,0.66); 
    border: 2px  solid rgba(0,0,0,0.5); 
    border-radius: 4px; padding: 8px;
}
<aside draggable="true" id="dragme">
    This is an aside, drag me.
</aside>
<p>I never am really satisfied that I understand anything; because, understand it well as I may, my comprehension can only be an infinitesimal fraction of all I want to understand about the many connections and relations which occur to me, how the matter in question was first thought of or arrived at, etc., etc.</p>
<p>In almost every computation a great variety of arrangements for the succession of the processes is possible, and various considerations must influence the selections amongst them for the purposes of a calculating engine. One essential object is to choose that arrangement which shall tend to reduce to a minimum the time necessary for completing the calculation.</p>
<p>Many persons who are not conversant with mathematical studies imagine that because the business of [Babbage’s Analytical Engine] is to give its results in numerical notation, the nature of its processes must consequently be arithmetical and numerical, rather than algebraical and analytical. This is an error. The engine can arrange and combine its numerical quantities exactly as if they were letters or any other general symbols; and in fact it might bring out its results in algebraical notation, were provisions made accordingly.</p>
<p>The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. It can follow analysis, but it has no power of anticipating any analytical revelations or truths. Its province is to assist us in making available what we are already acquainted with.</p>

</div>
  • 写回答

1条回答 默认 最新

  • dscqrkvr9562034621 2016-06-10 12:48
    关注

    I have changed only 2 lines in your javascript code. I have replaced setting and getting cookie data with localStorage methods setItem() and getItem().

    Regarding, how long localStorage keeps data stored, you can better checkout @Pointy's answer here. In short, it's not clear when this data will be cleared (usually it stays long enough in the browser ), but you can clear or update that data any time you want using localStorage.setItem() and localStorage.clearItem() methods.

    function drag_start(event) {
        var style = window.getComputedStyle(event.target, null);
        event.dataTransfer.setData("text/plain",
        (parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
    } 
    function drag_over(event) { 
        event.preventDefault(); 
        return false; 
    } 
    function drop(event) { 
        var offset = event.dataTransfer.getData("text/plain").split(',');
        var dm = document.getElementById('dragme');
        dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
        dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
        var pos = {left: dm.style.left, top: dm.style.top};
        console.log( pos );
        localStorage.setItem("div_position", JSON.stringify(pos));
        event.preventDefault();
        return false;
    }
    var dm = document.getElementById('dragme'); 
    try {
      var pos = JSON.parse(localStorage.getItem("div_position"));
      dm.style.left = pos.left ? pos.left : '0px';
      dm.style.top = pos.top ? pos.top : '0px';
    } catch (e) {
      // Some error handling
    }
    dm.addEventListener('dragstart',drag_start,false); 
    document.body.addEventListener('dragover',drag_over,false); 
    document.body.addEventListener('drop',drop,false); 
    
    
    /*
    
    function drop(event) { 
        var offset = event.dataTransfer.getData("text/plain").split(',');
        var dm = document.getElementById('dragme');
        dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
        dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
        var pos = {left: dm.style.left, top: dm.style.top};
        var str = JSON.stringify(pos);
        var dat = <?php echo $_GET[date];?>;
        document.cookie = dat+"="+str;
        event.preventDefault();
        return false;
    }
    var dm = document.getElementById('dragme'); 
    try {
      var pos = JSON.parse(dat);
      dm.style.left = pos.left ? pos.left : '0px';
      dm.style.top = pos.top ? pos.top : '0px';
    } catch (e) {
      // Some error handling
    }
    */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊