这种效果该如何实现?

当按住鼠标左键不松开时,鼠标在浏览器窗口里移动,能够根据移动的位置画出走过的痕迹,鼠标左键松开时,画图功能不在执行,如果用点击事件很容易就能获取到每次点击的坐标,现在问题是该用什么方法,才能获取到鼠标经过的每一个坐标

阅读 3.3k
5 个回答

要完成这个效果,组合使用三个事件就可以了 mousedown mousemove mouseup

在鼠标移动的时候时刻获取鼠标的坐标

效果预览

html

<div class="drag-wrap" id="drag-wrap"></div>

css

body{
  background-color: #000;
}

.drag-wrap{
  width: 600px;
  height: 500px;
  margin: auto;
  background-color: #fff;
  position: relative;
  overflow: hidden;
}

.green-dot{
  width: 2px;
  height: 2px;
  border-radius: 100%;
  background-color: green;
  position: absolute;
}

js

var app = {
  init: function () {
    var oDragWrap = document.getElementById('drag-wrap');

    this.drag(oDragWrap);
  },
  cDiv: function (tagName, iClass) {
    var tag = document.createElement(tagName);

    tag.className = iClass ? iClass : '';

    return tag;
  },
  css: function (ele, styleObj) {
    for(var attr in styleObj){
      ele['style'][attr] = styleObj[attr];
    }
  },
  drag: function (obj) {
    var _this = this;
    var oDragWrap = document.getElementById('drag-wrap');
    var disX,disY,div;

    obj.onmousedown = function (ev) {
      var ev = ev || event;
      disX = this.offsetLeft;
      disY = this.offsetTop;

      document.onmousemove = function (ev) {
        var ev = ev || event;
        div = _this.cDiv('div', 'green-dot');

        _this.css(div, {
          left: ev.clientX - disX + 'px',
          top: ev.clientY  - disY + 'px'
        });

        oDragWrap.appendChild(div);
      }

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

      return false;
    }
  }
}

app.init();

各位道友给点思路

jquery mousemove 事件

  • $(document).mousemove(function(e){ })

javascript onmousemove 事件

取得当前鼠标的位置,就在click/mousemove等事件中的event对象中!
例如你绑定了一个mousemove对象,那么


elem.onmousemove(ev) {
    // 鼠标x,y坐标
    var pX = ev.clientX,
        pY = ev.clientY;
}

你还可以直接将event对象直接log出来,看看里面到底有哪些属性

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