js实现标签拖动
// F12,给要拖动的标签加个id my_wsh,然后控制运行如下JS即可实现标签拖放
var box = document.getElementById("my_wsh"); //获取元素
var x, y; //鼠标相对与div左边,上边的偏移
var isDrop = false; //移动状态的判断鼠标按下才能移动
box.onmousedown = function (e) {
var e = e || window.event; //要用event这个对象来获取鼠标的位置
x = e.clientX - box.offsetLeft;
y = e.clientY - box.offsetTop;
isDrop = true; //设为true表示可以移动
}
document.onmousemove = function (e) {
//是否为可移动状态
if (isDrop) {
var e = e || window.event;
var moveX = e.clientX - x; //得到距离左边移动距离
var moveY = e.clientY - y; //得到距离上边移动距离
//可移动最大距离
var maxX = document.documentElement.clientWidth - box.offsetWidth;
var maxY = document.documentElement.clientHeight - box.offsetHeight;
//范围限定 当移动的距离最小时取最大 移动的距离最大时取最小
//范围限定方法一
/*if(moveX < 0) {
moveX = 0
} else if(moveX > maxX) {
moveX = maxX;
}
if(moveY < 0) {
moveY = 0;
} else if(moveY > maxY) {
moveY = maxY;
} */
//范围限定方法二
moveX = Math.min(maxX, Math.max(0, moveX));
moveY = Math.min(maxY, Math.max(0, moveY));
box.style.left = moveX + "px";
box.style.top = moveY + "px";
} else {
return;
}
}
document.onmouseup = function () {
isDrop = false; //设置为false不可移动
}