JavaScript拖拽(一):简单拖拽

拖拽在前端开发中是很常见的功能,也是基本功之一,本文是不限制范围的拖拽也就是最简单的拖拽,鼠标按下对象,拖拽,松开停止!
1,onmousedown事件
2,onmousemove事件
3,onmouseup事件

因为在按下时拖动,所以onmousemove事件在down后才注册,up事件是用来解绑事件,消除事件!



<html>
<head>
    <meta charset="utf-8">
    <title>简单拖拽title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        #div1 {
            width: 100px;
            height: 100px;
            background: orange;
            position: absolute;
        }
    style>
head>
<body style="height: 500000px;">
    <div id="div1">div>

    <script type="text/javascript">
        function getStyle(obj, attr) {
            if (obj.currentStyle) {
                return obj.currentStyle[attr];
            } else {
                return getComputedStyle(obj, null)[attr];
            }
        }
        var oDiv = document.getElementById('div1');
        oDiv.onmousedown = function(ev) {
            var oEvent = ev || event;
            // var disX = oEvent.clientX - oDiv.offsetLeft;
            // var disY = oEvent.clientY - oDiv.offsetTop;

            var disX = oEvent.clientX - parseInt(getStyle(oDiv, 'left'));
            var disY = oEvent.clientY - parseInt(getStyle(oDiv, 'top'));

            document.onmousemove = function(ev) {
                var oEvent = ev || event;
                oDiv.style.left = oEvent.clientX - disX + 'px';
                oDiv.style.top = oEvent.clientY - disY + 'px';
            };
            document.onmouseup = function() {
                document.onmousemove = null;
                document.onmouseup = null;
            };
            return false;
        };
    script>
body>
html>

你可能感兴趣的:(前端,拖拽)