如何在拖动后限制其容器内的div?

时间:2017-04-17 14:05:14

标签: javascript drag

我想在其容器的边界内拖动一个div,我没有设法将拖动光标(橙色div)限制在其容器的限制范围内:当它在右边时它过多了在左边界和右边界。 这是JsFiddle:https://jsfiddle.net/k2dc8p8c/
和代码:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style media="screen">
body{
  width: 1500px; height: 1500px;
}
  #container{
    position:absolute;
    width: 300px; height: 80px; border: 1px solid red;
  }
  #cursor{
    position:absolute;
    width: 50px; height:100%;
    background-color: orange;
  }
  .dontSelect{
    -webkit-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;
  }
</style>
</head>
<body>

<div id="container" class="dontSelect">
  <div id="cursor" class="dontSelect"></div>
</div>

<script>
var cursor = document.getElementById("cursor");
var container = document.getElementById("container");
var isMouseDown = false;
var w = container.offsetWidth, startPosClick = 0;
var leftContainerStart = container.offsetLeft;
cursor.style.left = leftContainerStart + (w/2) - (cursor.offsetWidth/2)+"px";
var leftCursorStart = cursor.offsetLeft;
//events
document.body.addEventListener("mousemove", function(e){
  if (isMouseDown){
    var dx = e.clientX - startPosClick;//*** HERE ***
    if (dx + leftCursorStart > 0 && (leftCursorStart + dx) < (leftContainerStart+w-cursor.offsetWidth)){
      cursor.style.left = dx+leftCursorStart+"px";
    }
  }
});
cursor.addEventListener("mousedown", function(e){
  isMouseDown = true;
  startPosClick = e.clientX;
  leftCursorStart = cursor.offsetLeft;
});
document.body.addEventListener("mouseup", function(){
  isMouseDown = false;
});

</script>
</body>
</html>

由于

0 个答案:

没有答案