一个可拖拽元素

 小练习:

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

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

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

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

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

html文件如下 

<!DOCTYPE html>
<div class="item">
  <div class="tips-Wrapper">
    <div class="top"></div>
    <div class="bottom">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?</div>
  </div>
</div>
<script src="./index.js">
  </script>  
</html>
<style lang="less" scoped> 
  .item{
  width: 100%;
  height: 100%;
  position: relative;
}
.tips-Wrapper{
  position: absolute;
width: 400px;
height: 350px;
background: #dedede;
}
.top{
  height: 28px;
  background: rgb(199, 235, 243,0.3);
}
.bottom{
  height: calc(100% - 28px);
  background:rgba(249, 253, 253, 0.847);
  color: rgba(59, 56, 52, 0.426);
  padding: 15px;
  /* text-align: justify; */
}
</style>
  

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;
  };
};

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值