拖拽释放API案例: 鼠标任意拖拽cheems

218 阅读1分钟

实现步骤:

  1. 先写内容 HTML
  2. 再写样式 CSS
  3. 最后写行为 JavaScript

HTML内容代码:

<body>
    <h3>随着鼠标拖动而移动的cheems</h3>
    <img id="cheems" src="images/cheems.gif" alt="" />
</body>

CSS样式代码:

<style>
      body {
        margin: 0;
        position: relative;
      }
      img {
        position: absolute;
      }
</style>

JavaScript部分代码:

<script>
    // 拖动开始
    cheems.ondragstart = function (e) {
      console.log("事件源cheems开始拖动");
      offsetX = e.offsetX;
      offsetY = e.offsetY;
    };

    // 拖动中
    cheems.ondrag = function (e) {
      console.log("事件源cheems拖动中");
      var x = e.pageX;
      var y = e.pageY;
      console.log(x + "-" + y);
      // drag事件最后一刻, 无法读取鼠标的坐标, pageX和pageY都变为0
      if (x == 0 && y == 0) {
        return; //不处理拖动最后一刻X和Y都为0的情形
      }
      x -= offsetX;
      y -= offsetY;

      cheems.style.left = x + "px";
      cheems.style.top = y + "px";
    };

    // 拖动结束
    cheems.ondragend = function () {
      console.log("源对象cheems拖动结束");
    };
</script>
  

在Chrome页面中显示的效果如下:

image.png

自己动手玩玩挺有意思的哦~~