2 个回答
✓ 已被采纳

修改了一下:
image.pngimage.png

demo:

<style>
  #Drag {
      /*border: 5px solid #C4E3FD;*/
      background: #C4E3FD;
      width: 50px;
      height: 50px;
      top: 50px;
      left: 50px;
      z-index: 2;
  }
</style>

<div id="Drag" onmousedown="moveBind(this, event)">1</div>
</div>
<br />拖放状态:<span id="idShow">未开始</span>


<script>

  function moveBind(obj, evnt) {
      //获得元素坐标。
      var left = obj.offsetLeft;
      var top = obj.offsetTop;
      var width = obj.offsetWidth;
      var height = obj.offsetHeight;

      //计算出鼠标的位置与元素位置的差值。
      var cleft = evnt.clientX - left;
      var ctop = evnt.clientY - top;

      document.onmousemove = function (doc) {
          //计算出移动后的坐标。
          var moveLeft = doc.clientX - cleft;
          var moveTop = doc.clientY - ctop;

          //设置成绝对定位,让元素可以移动。
          obj.style.position = "absolute";

          //当移动位置在范围内时,元素跟随鼠标移动。
          obj.style.left = moveLeft + "px";
          obj.style.top = moveTop + "px";

          show("idShow", moveLeft, moveTop);
      }

      document.onmouseup = function () {
          document.onmousemove = function () { }
      };
  }

</script>

解决你的问题的核心是这个:
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题