首页 > 其他 > 详细

实现元素的拖拽

时间:2021-09-23 02:17:47      阅读:22      评论:0      收藏:0      [点我收藏+]

1.html

    <div id="test"></div>

2.css

   #test {
            width: 100px;
            height: 100px;
            background: #000;
            position: absolute;
            color: #fff;
	    cursor: pointer;
	    outline: none;
        }

3.js

        (function() {
            function Code() {}
            Code.prototype = {
                addEvent: function() {
                    var that = this;
                    var oDiv = document.getElementById(‘test‘);//与html要拖拽的元素id名相同
                    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();
        })();

实现元素的拖拽

原文:https://www.cnblogs.com/mywifeisMsHu/p/15307196.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!