拖拽div移动的两种方法

  • Post author:
  • Post category:其他


  1. jQuery UI – 拖动(Draggable)

    在任意的 DOM 元素上启用 draggable 功能。通过鼠标点击并在视区中拖动来移动 draggable 对象。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
<div id="main" style="width: 100px;height:100px;background-color: red"></div>
</body>
<script src="../frames/jquery-1.11.1.min.js"></script>
<script src="../frames/jquery-ui.js"></script>
<script type="text/javascript">
    $('#main').draggable({
        stop : function (e) {
            console.log(e)
            //储存位置信息
        }});
</script>
</html>

更多拖动的功能可以参考

jQuery UI 实例 – 拖动(Draggable)


2. 根据鼠标事件拖动div并计算在页面中的位置比例,例子如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        html{
            height: 100%;
        }
        body{
            /*height: calc(100% - 16px);*/
            margin:0;
            height: 100%;
        }
        #main{
            width: 100px;
            height:100px;
            background-color: red;
            position:absolute;
        }
    </style>
</head>
<body>
<div id="main"></div>
</body>
<script src="../frames/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
    drag();
    function drag() {
        var odrag = document.getElementById("main");
        odrag.onmousedown = function (ev) {
            var oevent = ev || event;
            var distanceX = oevent.clientX - odrag.offsetLeft;
            var distanceY = oevent.clientY - odrag.offsetTop;
            var old_x=oevent.clientX;
            var old_y=oevent.clientY;
            document.onmousemove = function (ev) {
                var oevent = ev || event;
                var _x, _y;
                _x = oevent.clientX - distanceX;
                _y = oevent.clientY - distanceY;
                if (_x < 0) _x = 0;
                if (_y < 0) _y = 0;
                if (_x > document.body.clientWidth - odrag.offsetWidth) _x = document.body.clientWidth  - odrag.offsetWidth;
                if (_y > document.body.clientHeight  - odrag.offsetHeight) _y = document.body.clientHeight  - odrag.offsetHeight;
                odrag.style.left = _x + 'px';
                odrag.style.top = _y + 'px';
            };
            document.onmouseup = function (ev) {
                var oevent = ev || event;
                var _x = oevent.clientX - distanceX;
                var _y = oevent.clientY - distanceY;

                var leftindex=(_x/$("body").width()).toFixed(2);
                var topindex=(_y/$("body").height()).toFixed(2);
                //存储位置区域比列或者具体数据
                document.onmousemove = null;
                document.onmouseup = null;
            };
        }
    }

</script>
</html>



版权声明:本文为qq_43155489原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。