元素拖拽

元素拖拽

    <hr>

    <style>
        #box{
            position: fixed;
            width:200px;
            height:200px;
            background:#ccc;
            cursor:pointer;
        }
    </style>
    <div id="box"></div>


    <script>
        //获取元素
        var box = document.getElementById("box");


        //绑定事件
        box.onmousedown = function(ev){
            var e = ev || window.event;

            //计算 鼠标在元素上的坐标
            var left = e.clientX - box.getBoundingClientRect().left;
            var top = e.clientY - box.getBoundingClientRect().top;


            this.onmousemove = function(ev){
                var e = ev || window.event; //
                //改变元素位置
                box.style.left = (e.clientX - left) + "px";
                box.style.top = (e.clientY - top) + "px";

            }
        }


        box.onmouseup = function(){
            this.onmousemove = function(){
                
            }
        }
    </script>

猜你喜欢

转载自www.cnblogs.com/1666818961-lxj/p/9263183.html