标签:
var login = document.getElementById(‘box‘); login.onmousedown = function(e) { var e = getEvent(e);//获取event对象 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; }
标签:
原文地址:http://www.cnblogs.com/lxdd/p/4203745.html