实现简单的盒子拖拽效果

<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex,nofollow">
<title>拖拽效果</title>
</head>
<style type="text/css">
	body{
		overflow: hidden;
	}
	#box{
		width: 200px;
		height: 200px;
		background: lightblue;
		cursor: move;
		position: absolute;
		top: 88px;
		left:33px;
	}
</style>
<body>
	<div id="box"></div>
	<script type="text/javascript">
	  var box = document.querySelectorAll('#box')[0]

	  box.addEventListener('mousedown', down)
	  // 获取当前视窗的宽度和高度,可自行更换实际容器的宽高
	  // 边界值需要减去盒子的宽高
	  let cw = document.documentElement.clientWidth - box.offsetWidth, ch = document.documentElement.clientHeight - box.offsetHeight
	  function down(e) {
	  	//当前盒子距离容器的左偏移量
	  	this.startL = this.offsetLeft
	  	//当前盒子距离容器的上偏移量
	  	this.startT = this.offsetTop
	  	//鼠标按下时的位置
	  	this.startX = e.clientX
	  	this.startY = e.clientY
	  	//使用bind改变this指向,使其指向box
	  	this.move = move.bind(this)
	  	this.up = up.bind(this)
	  	//鼠标按下后给document绑定mousemove以及mouseup事件
	  	document.addEventListener('mousemove', this.move)
	  	document.addEventListener('mouseup', this.up)
	  }
	  
	  function move(e) {
	  	// 定义变量:用当前鼠标的位置 - 初始的鼠标位置 + 盒子的宽度/高度
	  	let curL = e.clientX - this.startX +this.startL,
	  	curT = e.clientY - this.startY +this.startT
	  	// 边界值判断
	  	curL = curL < 0 ? 0 : (curL > cw ? cw : curL)
	  	curT = curT < 0 ? 0 : (curT > ch ? ch : curT)
	  	this.style.cssText = `top:${curT}px;left:${curL}px`
	  }
	  
	  function up(e) {
	  	//鼠标抬起,document解绑事件
	  	document.removeEventListener('mousemove', this.move)
	  	document.removeEventListener('mouseup', this.up)
	  }
	</script>
</body>
</html>

以上代码复制粘贴就可以用,可以实现简单的拖拽效果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值