javascript - 这种效果该如何实现?
阿神
阿神 2017-04-11 10:24:01
[JavaScript讨论组]

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

阿神
阿神

闭关修行中......

全部回复(5)
PHP中文网

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

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

效果预览

html

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

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);
  },
  cp: 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,p;

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

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

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

        oDragWrap.appendChild(p);
      }

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

      return false;
    }
  }
}

app.init();
巴扎黑

各位道友给点思路

阿神

http://www.cnblogs.com/lgmcolin/archive/2013/02/16/2913268.html

canvas画图板。

怪我咯

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);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号