div拖拽实现延伸

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/caomage/article/details/81015950

div拖拽

原理:

鼠标事件

  1. mousedown
  2. mousemove
  3. mouseup

注意事项:

  1. 被拖动的div的position属性值一定是absolute。
  2. onmousedown事件需要在window.onload时加载。
  3. 如果被拖动的div上有文字会有自带的文字拖动效果,需要将改div上的所有拖动事件绑定在该div上,可以使用setCapture。

代码:

html&css:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="test.js"></script>
    <style>
        #test {
            width: 100px;
            height: 100px;
            background: #000;
            position: absolute;
            color: #fff;
        }
    </style>
</head>
<body>
    <div id="test">4616125</div>
</body>
</html>

js

/*
 * @Author: lee
 * @Date: 2018-07-10 11:40:31 
 * @Last Modified by: lee
 * @Last Modified time: 2018-07-10 16:10:49
 */
(function() {
    function Code() {}
    Code.prototype = {
        addEvent: function() {
            var that = this;
            var oDiv = document.getElementById('test');
            oDiv.onmousedown = function(ev) {
                var ev = ev || event;
                var distanceX = ev.clientX - this.offsetLeft;
                var distanceY = ev.clientY - this.offsetTop;
                if (oDiv.setCapture) {
                    oDiv.setCapture();
                }
                document.onmousemove = function(ev) {
                    var ev = ev || event;
                    oDiv.style.left = ev.clientX - distanceX + 'px';
                    oDiv.style.top = ev.clientY - distanceY + 'px';
                };
                document.onmouseup = function(ev) {
                    document.onmousemove = document.onmouseup = null;
                    if (oDiv.releaseCapture) {
                        oDiv.releaseCapture();
                    }
                };
            };
        },

        init: function() {
            var that = this;
            window.onload = that.addEvent;
        },
    }
    new Code().init();
})();

新博客地址:http://www.caomage.com

展开阅读全文

没有更多推荐了,返回首页