简单拖拽保存

41 阅读1分钟

title: 简单拖拽保存 date: 2014-04-15 15:59:05 tags: js category: javascript

<html>
<head>
    <title>提示</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
        .drag{
            width:200px;
            height:200px;
            background:rgba(204,255,102,1);
            position:absolute;
            cursor:move;
            top:100px;left:20px;
            text-align:center;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script>


        $(function () {
            if(window.localStorage){
                $(".drag").css({top:localStorage.getItem("top"),left:localStorage.getItem("left") });
            }

            var _move = false; //移动标记
            var _x, _y; //鼠标离控件左上角的相对位置
            $(".drag").click(function () {

                // alert("click");
                //点击(松开后触发)
            }).mousedown(function (e) {
                //alert("111");
                //alert(_move);
                _move = true;
                _x = e.pageX - parseInt($(".drag").css("left"));
                _y = e.pageY - parseInt($(".drag").css("top"));
                $(".drag").fadeTo(20, 0.5); //点击后开始拖动并透明显示
            });
            $(document).mousemove(function (e) {

                if (_move) {
                    var x = e.pageX - _x; //移动时根据鼠标位置计算控件左上角的绝对位置
                    var y = e.pageY - _y;
                    $(".drag").css({
                        top: y,
                        left: x
                    }); //控件新位置
                    window.localStorage.setItem("top",y);
                    window.localStorage.setItem("left",x);
                }
            }).mouseup(function () {
                _move = false;
                $(".drag").fadeTo("fast", 1); //松开鼠标后停止移动并恢复成不透明
            });
        });
    </script>
</head>
<body >
<div class="drag">O(∩_∩)O哈哈~</div>
</body>
</html>