1. 程式人生 > >滑鼠事件點選拖拽div

滑鼠事件點選拖拽div

<div id="div1"></div>

#div1{
	width:100px;
	height: 100px;
	background:red;
	position: absolute;
}

window.onload = function() {

    var oDiv = document.getElementById('div1');

    var disX = 0;

    var disY = 0;

    //1. 滑鼠按下
    oDiv.onmousedown = function(ev) {

        var oEvent = ev || event;

        disX = oEvent.clientX - oDiv.offsetLeft;

        disY = oEvent.clientY - oDiv.offsetTop;

        //2. 滑鼠移動  
        document.onmousemove = function(ev) {

            var oEvent = ev || event;
            var l = oEvent.clientX - disX;
            var t = oEvent.clientY - disY;

            if (l < 0) {
                l = 0;
            } else if (l > document.documentElement.clientWidth - oDiv.offsetWidth) {

                l = document.documentElement.clientWidth - oDiv.offsetWidth;
            }
            if (t < 0) {
                t = 0;
            } else if (t > document.documentElement.clientHeight - oDiv.offsetHeight) {
                t = document.documentElement.clientHeight - oDiv.offsetHeight;
            }
            oDiv.style.left = l + 'px';
            oDiv.style.top = t + 'px';
        };
        //3.鬆開滑鼠
        document.onmouseup = function() {

            document.onmousemove = null;

            document.onmouseup = null;
        };
        //阻止預設事件
        return false;;
    };
};