JS 简单拖拽
var login = document.getElementById('box'); login.onmousedown = function(e,tags) {//tags是个数组对象 var e = getEvent(e);//获取event对象 //判断是不是点击头区域 //if(e.target.className != 'login_title') // return; //直接判断classname或者tagname太死板,容易出问题,改为对象 var flag = false;//标识符 for(var i = 0;i<tags.length;i++) { if(tags[i] == e.target) { flag = true; break;//为true立即停止循环 } } if(flag) { var _this = this; var diffX = e.clientX - _this.offsetLeft;//鼠标点击的坐标点x减去box元素距离左边的距离,得到的差为鼠标垫距离box元素左边的距离 var diffY = e.clientY - _this.offsetTop;
document.onmousemove = function(e) { //第一种方式,每次判断,然后给box元素的left赋值 if(e.clientX - diffX <= 0) { _this.style.left = '0px'; }else if(e.clientX - diffX >= document.body.clientWidth - _this.offsetWidth) { _this.style.left = (document.body.clientWidth - _this.offsetWidth) + 'px'; }else { _this.style.left = (e.clientX - diffX) + 'px'; } //这种方法更简洁,好看 var top = e.clientY - diffY; if(top <= 0) top = 0; else if(top >= document.body.clientHeight - _this.offsetHeight) top = document.body.clientHeight - _this.offsetHeight _this.style.top = top + 'px'; } document.onmouseup = function() { //鼠标放开后,注销移动跟放开的事件 this.onmousemove = null; this.onmouseup = null; } } } function getEvent(event) { return event || window.event; }