原生js实现拖拽的小案例,欢迎指正!
布局:
<div id="box">
<div id="ball"></div>
</div>
样式:
html,body,div{
margin: 0;
padding: 0;
}
#box{
width: 500px;
height: 500px;
margin: 50px auto;
border: 1px solid;
position: relative;
}
#box>#ball{
width: 80px;
height: 80px;
background: lawngreen;
position: absolute;
cursor: pointer;
}
逻辑代码:
// onmousedown\onmouseup\onmousemove拖拽三个事件
//父函数
function Fa(oBox,oBall) {
this.oBox = oBox;
this.oBall = oBall;
var that = this;
this.oBall.onmousedown = function () {
// event兼容写法
var event = event || window.event;
// 获取鼠标按下时的x,y坐标
var x1 = event.clientX;
var y1 = event.clientY;
// 获取移动是盒子距离上边界、左边界的距离
var L = that.oBall.offsetLeft;
var T = that.oBall.offsetTop;
document.onmousemove = function (event) {
// 鼠标移动后的坐标值
var x2 = event.clientX;
var y2 = event.clientY;
// 计算盒子偏移的值等于鼠标移动后坐标-鼠标刚按下值+盒子距离边界偏移量
var x = x2 - x1 + L;
var y = y2 - y1 + T;
// 盒子可移动宽度 = 盒子外层盒子宽度-盒子的自身宽度
var max = that.oBox.clientWidth - that.oBall.offsetWidth;
var may = that.oBox.clientHeight - that.oBall.offsetHeight;
if (x < 0) {
x = 0;
}
if (x > max) {
x = max;
}
if (y < 0) {
y = 0;
}
if (y > may) {
y = may;
}
// 设置盒子的left值top值
that.oBall.style.left = x + 'px';
that.oBall.style.top = y + 'px';
}
// 移动事件失效
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
}
//子函数
function Son() {
var oBox = document.getElementById('box');
var oBall = document.getElementById('ball');
//改变this指向
Fa.call(this, oBox,oBall)
}
Son();