div元素随着鼠标进行移动

原理

  • div元素的位置和鼠标的位置一致,鼠标位置采用事件的e.clientX和e.clientY值,div元素采用定位
  • 用top和left设置位置,鼠标的位置是根据浏览器窗口的,div是根据他相对定位的元素进行定位的
  • 转化,需要把鼠标位置,转为div元素位置,一般采用减去offsetTop和offsetLeft。

事件监听过程

  • 鼠标按下进行开始移动,给元素添加mousedown事件,开启监听mousemove事件,mousemove事件需要添加到document,所以需要有一个变量进行控制mosermove事件的操作,如下代码:
$('.colorSelect').on('mousedown', function (e) {
    isDrag = true;
});

$(document).on('mousemove', function (e) {
    mouseMove(e, isDrag, offsetTop, offsetLeft)
    if (isDrag) {
        ...
    }
});

$(document).on('mouseup', function (e) {
    isDrag = false;
});

总结

  • 由输入和输出思考中间变化过程
posted @ 2017-06-26 17:45  风烟  阅读(1032)  评论(0编辑  收藏  举报