JavaScript How to Dynamically Move Div by Clicking and Dragging

前端 未结 6 1888
滥情空心
滥情空心 2020-12-23 14:06

Okay it would seem like it should be simple. I need to take an already existing div and move it according to mouse position within the window. I have searched everywhere and

6条回答
  •  隐瞒了意图╮
    2020-12-23 14:41

    I just made a small change to the @adeneo very well working answer. If everything is enclosed in a function, and every event is attached to the div, you can use it as part of a library.

    Call the following function passing an id. If the div does not exist it is created.

    function drag_div(div_id){
    var div;
    
    div = document.getElementById(div_id);
    
    if(div == null){
       div = document.createElement("div");
       div.id = div_id;
       div.style.position = "absolute";
       div.style.left = "0px";
       div.style.top = "0px";
       div.style.width = "100px";
       div.style.height = "100px";
       div.style.background = "red";
       div.style.color = "blue";
       document.body.appendChild(div);
    }
    
    div.addEventListener('mousedown', function(e) {
        div.isDown = true;
        div.offset = [
            div.offsetLeft - e.clientX,
            div.offsetTop - e.clientY
        ];
    }, true);
    
    div.addEventListener('mouseup', function() {
        div.isDown = false;
    }, true);
    
    div.addEventListener('mousemove', function(event) {
        event.preventDefault();
        if (div.isDown) {
            div.mousePosition = {
    
                x : event.clientX,
                y : event.clientY
    
            };
            div.style.left = (div.mousePosition.x + div.offset[0]) + 'px';
            div.style.top  = (div.mousePosition.y + div.offset[1]) + 'px';
        }
    }, true);
    }
    

提交回复
热议问题