鼠标拖拽效果
使用js实现鼠标点击div实现拖拽效果,物体跟随鼠标进行移动
功能效果要点:
鼠标在物体内按下不松之后,鼠标移动,物体跟随鼠标位置发生移动,实现鼠标拖拽效果,下方代码实现的是拖拽图片进行移动的效果;
**如果是图片,需要清除一下图片标签在浏览器中的默认事件**
```javascript
var o = document.getElementById('box');//移动的物体
var vH=document.documentElement.clientHeight;//视图的高度
var vW=document.documentElement.clientWidth;//视图的宽度
//添加鼠标按下事件
o.onmousedown = function (e) {
e = e || window.event;
//鼠标距离物体的相对位置(left,top)
var disX = e.clientX - this.offsetLeft,
disY = e.clientY - this.offsetTop;
//判断,若是在低版本IE上,为物体添加全局捕获
if (o.setCapture) {
o.setCapture();
}
//鼠标移动
document.onmousemove = function (e) {
e = e || window.event;
var x = e.clientX - disX;//物体位置=鼠标的位置-鼠标相对于物体的位置
var y = e.clientY - disY;//物体位置
//判断边界问题
if(x<0){
x=0;//最左边
}else if(x>vW-o.offsetWidth){
x=vW-o.offsetWidth;//最右边
}
if(y<0){
y=0;//最上边
}else if(y>vH-o.offsetHeight){
y=vH-o.offsetHeight;
}
//在鼠标移动过程中,修改物体的位置
o.style.left = x + "px";
o.style.top = y + 'px';
};
//鼠标抬起
document.onmouseup = function () {
// console.log('up');
document.onmousemove = null;
document.onmouseup = null;
//释放全局捕获
if(o.releaseCapture){
o.releaseCapture();
}
};
return false;//拦截浏览器的默认行为
};