一个可拖拽元素

 小练习:

写了一个可拖拽元素,按住顶部工具条可拖动至任意位置,但不能超出浏览器边框,按照这几个步骤完成即可,并配图食用更好理解

  1. 记录鼠标按下的坐标,就是⚪的坐标
  2. 获取该元素的坐标 ,即算出矩形距离左边、顶部距离(ex,ey)

  3. 鼠标按下后,监听整个屏幕的鼠标移动,可根据抬起点位坐标(e.clientX,e.clientY)计算出鼠标移动的距离

  4. 移动到新位置,计算该元素至浏览器左边距离,用初始位置距离左边距离ex加上移动距离disX,计算该元素至浏览器顶部距离同理

  5. 鼠标抬起后,不再监听鼠标移动和抬起,监听事件设置为null

一个可拖拽元素_第1张图片

html文件如下 


Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum est temporibus doloremque eos inventore, doloribus aspernatur eius numquam provident optio voluptate quos asperiores cupiditate ducimus neque iste perferendis ab sed?

index.js文件如下 

var moveArea = document.getElementsByClassName('top')[0];
var note = document.getElementsByClassName('tips-Wrapper')[0];
//一开始保存至变量,用变量不会导致重排,用属性会导致重排
moveArea.onmousedown = function (e) {
  console.log('onmousedown', e);
  //记录鼠标按下的坐标
  var x = e.clientX;
  var y = e.clientY;
  var rect = moveArea.getBoundingClientRect();
  //该元素的坐标
  var ex = rect.left;
  var ey = rect.top;
  console.log('rect', rect);
  //获取视口宽高、元素宽高
  var w = document.documentElement.clientWidth,
    h = document.documentElement.clientHeight;
  var ew = note.offsetWidth,
    eh = note.offsetHeight;
  //算出最大的left top
  var maxLeft = w - ew;
  var maxTop = h - eh;
  //鼠标按下后,监听整个屏幕的鼠标移动
  window.onmousemove = function (e) {
    console.log('onmousemove', e);
    var disX = e.clientX - x;
    var disY = e.clientY - y;
    var left = ex + disX;
    var top = ey + disY;
    if (left < 0) {
      left = 0;
    }
    if (left > maxLeft) {
      left = maxLeft;
    }
    if (top < 0) {
      top = 0;
    }
    if (top > maxTop) {
      top = maxTop;
    }
    console.log('note', note);
    note.style.left = left + 'px';
    note.style.top = top + 'px';
  };
  //鼠标抬起后,不再监听鼠标移动和抬起
  window.onmouseup = function (e) {
    console.log('onmouseup', e);
    window.onmousemove = null;
    window.onmouseup = null;
  };
};

你可能感兴趣的:(javascript,开发语言,ecmascript)