javascript - 是否可以获取 View 上每个 div 的坐标并将它们保存在 javascript onunload() 函数中的本地存储中?

标签 javascript html asp.net-mvc-4 local-storage jquery-ui-draggable

我有一个包含两个保存图像的 div 的 View 。我已经实现了 JQuery 的可拖动功能,并将两个 div 都放在一个容器中。我想在用户离开 View 和/或刷新 View 时将 div 的坐标保存在本地存储中。存储在数据库中不适合我目前的情况。

 $(document).ready(function () {

    $('#pieChart').draggable
    ({
            containment: $("#myContainer"),
            cursor: "hand",
            opacity: 0.75
    });

    $('#lineChart').draggable
    ({
        containment: $("#myContainer"),
        cursor: "hand", 
        opacity: 0.75
    });
});


window.onunload = function () {

    //get the coordinates of all divs
}

任何帮助实现这一点的人都很棒!!!

最佳答案

休息一下,然后重新审视这个问题,我能够达到预期的效果,并希望分享希望在未来的情况下帮助其他人。

 $(document).ready(function () {

    $("#pieChart").parent().css({ position: "relative" });
    $("#lineChart").parent().css({ position: "relative" });

    $("#pieChart").css({ top: localStorage["pieTop"], left: localStorage["pieLeft"], position:"absolute" });
    $("#lineChart").css({ top: localStorage["lineTop"], left: localStorage["lineLeft"], position:"absolute" });

    $("#pieChart").draggable
    ({
        containment: $("#myContainer"),
        cursor: "hand",
        opacity: 0.75,
    });

    $("#lineChart").draggable
    ({
        containment: $("#myContainer"),
        cursor: "hand", 
        opacity: 0.75
    });
});


$("#pieChart").draggable(
    {
        stop: function (event, ui) {
            console.log(event);

            localStorage["pieTop"] = ($('#pieChart').position().top); //offset top
            localStorage["pieLeft"] = ($('#pieChart').position().left); //offset left
        }
    });

$("#lineChart").draggable(
    {
        stop: function (event, ui) {
            console.log(event);

            localStorage["lineTop"] = ($('#lineChart').position().top); //offset top
            localStorage["lineLeft"] = ($('#lineChart').position().left); //offset left
        }
    });

以上代码检索 div 的“顶部”和“左侧”偏移量并将它们放置在本地存储中。在重新加载/刷新页面时,div 将根据先前存储的偏移量进行定位。这是通过使父页面“相对”和 div“绝对”以及在每次可拖动事件停止时记录偏移量来实现的。

关于javascript - 是否可以获取 View 上每个 div 的坐标并将它们保存在 javascript onunload() 函数中的本地存储中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31615231/

相关文章:

Javascript 'number' 和 postgres 类型

javascript - 如何从数据表中删除一些元素?

azure - 在 Azure 云服务中将 Web 套接字服务器实现为 Web 角色

javascript - 如何解决 $q 的 promise ?

javascript - 使默认值适用于对象参数的各个字段

html - 在同一行中与图像一起显示文本?

javascript - Bootstrap 确认主模态后面的模态

javascript - JS/jQuery 适合 div 内的所有图像(无空格)

c# - 如何在服务中获取 Controller 的 ModelState 以进行验证

asp.net-mvc-4 - ASP.Net MVC4 移动感知输出缓存