如何通过单击和拖动来动态移动Div

时间:2018-06-30 10:56:13

标签: javascript html css

我想在单击鼠标后根据父div中的鼠标位置移动div。当我们离开鼠标指针时,请设置div的位置。 我到处搜索,这导致我做相同事情的方法过于复杂,涉及到j查询的使用。我需要严格使用javascript进行操作。

这是 css代码

function submit_forms(form_id){

   var avoid_duplicate_form_submission = 0;      

    $("#"+form_id).submit(function(e){           
       e.preventDefault();  

         avoid_duplicate_form_submission++;

         if(avoid_duplicate_form_submission === 1){

                    // All your code....  
            }

    });    

}

这是 html代码

body {
    margin: 0px;
    padding: 0px;
}
.crop-container{
    width: 500px;
    height: 500px;
    border:5px solid black;
    position: relative;
}
.crop-lense{
    width: 100px;
    height: 100px;
    border: 5px dotted black;
    position: relative;
    z-index: 10;
    resize: both;
    background-color: transparent;
}

这是 javascript代码

<div class="crop-container" id="container" onmousemove="showCoords(event)">
    <div class="crop-lense" id="lense">

    </div>
</div>

1 个答案:

答案 0 :(得分:1)

最短的答案:

var lense = document.getElementById("lense");
var container = document.getElementById("container");
var x;
var y;

lense.addEventListener("mousedown", function() {
  lense.addEventListener("mousemove", showCoords)
});

lense.addEventListener("mouseup", removeListener);
lense.addEventListener("mouseout", removeListener);

function removeListener() {
  lense.removeEventListener("mousemove", showCoords)
}

function showCoords(event) {
 if(container.offsetWidth >= event.pageX + lense.offsetWidth / 2 + 10 &&
   container.offsetHeight >= event.pageY + lense.offsetHeight / 2 + 10 &&
   event.pageX - lense.offsetWidth / 2 > 0 &&
   event.pageY - lense.offsetHeight / 2 > 0){
    x = event.pageX - lense.offsetWidth / 2;
    y = event.pageY - lense.offsetHeight / 2;
    lense.style.top = y + "px";
    lense.style.left = x + "px";
  }
}
 body {
            margin: 0px;
            padding: 0px;
          }
          .crop-container{
            width: 500px;
            height: 500px;
            border:5px solid black;
            position: relative;
          }
          .crop-lense{
            width: 100px;
            height: 100px;
            border: 5px dotted black;
            position: relative;
            z-index: 10;
            resize: both;
            background-color: transparent;
            t
          }
<div class="crop-container" id="container">
  <div class="crop-lense" id="lense">

  </div>
</div>