js实现模态窗口的拖拽功能
一.用到的几个基本概念:
(1)document.body.clientWidth/clientHeight:获得BODY对象宽度/高度
(2)document.documentElement.clientWidth/clientHeight:用来获得可见区域宽度/高度。
clientWidth/clientHeight的计算方法:
(3)offsetParent 是一个只读属性,返回一个指向最近的(closest,指包含层级上的最近)包含该元素的定位元素。如果没有定位的元素,则 offsetParent 为最近的 table 元素对象或根元素(标准模式下为 html;quirks 模式下为 body)。
offsetLeft:获取对象相对于页面或由 offsetParent 属性指定的父坐标的计算左侧位置
offsetTop:获取对象相对于页面或由 offsetTop 属性指定的父坐标的计算顶端位置
offsetWidth/offsetHeight计算方法:
(4)clientX/clientY :事件属性返回当事件被触发时鼠标指针向对于浏览器页面(当前窗口)的水平坐标/垂直坐标(不包含滚动条)。
二.拖拽的主要实现思想
分为三步:
(1)用户在拖放元素上按下鼠标,拖放开始
login.addEventListener("mousedown",drag,false);
(2)用户在拖放元素上移动鼠标,拖放元素在页面中进行拖动
document.addEventListener("mousemove",move,false);
(3)用户鼠标一开拖放元素,拖放行为结束
document.addEventListener("mouseup",up,false);
三.实现具体js代码
window.onload=function(){varclose=document.getElementsByClassName('close');varlogin=document.getElementById('login');varlogins=document.getElementsByClassName('login');varscreen=document.getElementById('dropback');functionshow(obj){//获取浏览器的宽和高vartop=(document.documentElement.clientHeight-250)/2-150;varleft=(document.documentElement.clientWidth-300)/2;//当点击登录按钮时,登录弹窗出现,遮罩层显示screen.style.display='block';//遮罩层显示obj.style.display='block';//登录弹窗出现obj.style.left=left+'px';//登录弹窗在屏幕中的位置obj.style.top=top+'px';}functionhide(obj){//点击差号时,登录弹窗消失,遮罩层消失obj.style.display='none';screen.style.display='none';}//差号注册点击事件点击差号,弹窗消失close[0].addEventListener("click",function(){hide(login);},false);//登录按钮注册点击事件,点击登录弹出登录弹窗logins[0].addEventListener("click",function(){show(login);},false);//弹出框拖拽实现login.addEventListener("mousedown",drag,false);functiondrag(e){vare=e||window.event;var_this=this;vardiffX=e.clientX-_this.offsetLeft;vardiffY=e.clientY-_this.offsetTop;document.addEventListener("mousemove",move,false);document.addEventListener("mouseup",up,false);functionmove(e){varleft=e.clientX-diffX;vartop=e.clientY-diffY;if(left<0){left=0;}elseif(left>document.documentElement.clientWidth-e.clientX){//没有使用document.body.clientWidth因为此时页面的高度只有100多,而现在要求弹窗在整个可视区中移动left=document.documentElement.clientWidth-_this.offsetWidth;}if(top<0){top=0;}elseif(top>document.documentElement.clientHeight-e.clientY){top=document.documentElement.clientHeight-_this.offsetHeight;}_this.style.left=left+'px';_this.style.top=top+'px';}functionup(){document.removeEventListener("mousemove",move,false);document.removeEventListener("mouseup",up,false);}}}
四.实现效果图,随着鼠标的拖拽,弹窗会在整个可视区进行移动
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。