js实现限定范围拖拽的示例

2022-07-28,,,

限定范围拖拽

目录

  • 代码实例
  • 与简易拖拽的差异
  • 下载源码链接 

代码实例

* {
 padding: 0;
 margin: 0;
}
#box1 {
 width: 500px;
 height: 500px;
 background: #999;
 position: relative;
 left: 100px;
 top: 100px;
}
#box {
 width: 100px;
 height: 100px;
 background: #334;
 position: absolute;
 cursor: move;
}

<div id="box1">
<div id="box"></div>
</div>

(function () {
 var dragging = false
 var boxx, boxy, mousex, mousey, offsetx, offsety
 var box = document.getelementbyid('box')
 var box1 = document.getelementbyid('box1')

 // 鼠标按下的动作
 box.onmousedown = down
 // 鼠标的移动动作
 document.onmousemove = move
 // 释放鼠标的动作
 document.onmouseup = up

 // 鼠标按下后的函数,e为事件对象
 function down(e) {
  dragging = true

  // 获取元素所在的坐标
  boxx = box.offsetleft
  boxy = box.offsettop

  // 获取鼠标所在的坐标
  mousex = parseint(getmousexy(e).x)
  mousey = parseint(getmousexy(e).y)

  // 鼠标相对元素左和上边缘的坐标
  offsetx = mousex - boxx
  offsety = mousey - boxy
 }

 // 鼠标移动调用的函数
 function move(e){
  if (dragging) {
   // 获取移动后的元素的坐标
   var x = getmousexy(e).x - offsetx
   var y = getmousexy(e).y - offsety

   // 计算可移动位置的大小, 保证元素不会超过可移动范围
   // 此处就是父元素的宽度减去子元素宽度
   var width = box1.clientwidth - box.offsetwidth
   var height = box1.clientheight - box.offsetheight

   // min方法保证不会超过右边界,max保证不会超过左边界
   x = math.min(math.max(0, x), width)
   y = math.min(math.max(0, y), height)

   // 给元素及时定位
   box.style.left = x + 'px'
   box.style.top = y + 'px'
  }
 }

 // 释放鼠标的函数
 function up(e){
  dragging = false
 }

 // 函数用于获取鼠标的位置
 function getmousexy(e){
  var x = 0, y = 0
  e = e || window.event

  if (e.pagex) {
   x = e.pagex
   y = e.pagey
  } else {
   x = e.clientx + document.body.scrollleft - document.body.clientleft
   y = e.clienty + document.body.scrolltop - document.body.clienttop
  }
  return {
   x: x,
   y: y
  }
 }
})()

与简易拖拽的差异

可移动位置的改变

// 此处就是父元素的宽度减去子元素宽度
var width = box1.clientwidth - box.offsetwidth
var height = box1.clientheight - box.offsetheight

下载源码链接

星辉的github

以上就是js实现限定范围拖拽的示例的详细内容,更多关于js实现限定范围拖拽的资料请关注其它相关文章!

《js实现限定范围拖拽的示例.doc》

下载本文的Word格式文档,以方便收藏与打印。