最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
原生js实现可拖动的登录框效果
时间:2017-02-28 编辑:简简单单 来源:一聚教程网
实现原理
1.onmousemove事件触发时不断更新鼠标的pageXY改变位置,
登陆框的偏移量=鼠标当前位置-鼠标到登录框边框的距离
2.onmousedown鼠标摁下时触发事件获取鼠标到登陆框的距离,再设置true允许拖拽
3.onmouseup 鼠标弹起设置false停止拖拽
4.登录框居中显示公式:(可视区域宽高-登录框宽高)/2
5.当浏览器窗口大小变化时触发事件window.onresize 再更新登陆框居中显示
代码中有详细的注释
完整代码
代码如下 | 复制代码 |
function b(){ //创建遮罩层div并插入body var mask=document.createElement("div"); mask.id="mask"; mask.style.height=cheight+"px"; //宽度直接用100%在样式里 document.body.appendChild(mask); //创建登录层div并插入body var login=document.createElement("div"); login.id="login"; login.innerHTML=' ' document.body.appendChild(login); //窗口可视区域宽度 var cwidth= document.documentElement.clientWidth || document.body.clientWidth; //窗口可视区域高度 var cheight= document.documentElement.clientHeight || document.body.clientHeight; //登录框宽度 var lwidth=login.offsetWidth; //登录框高度 var lheight=login.offsetHeight; //设置登录框的居中显示 login.style.left=(cwidth-lwidth)/2+"px"; login.style.top=(cheight-lheight)/2+"px"; //设置遮罩层的高度 mask.style.height=cheight+"px"; //改变窗口大小后依然居中显示 window.onresize=function(){ if(document.compatMode=="CSS1Compat"){ cwidth=document.documentElement.clientWidth; cheight=document.documentElement.clientHeight; }else{ cwidth=document.body.clientWidth; cheight=document.body.clientHeight; } login.style.left=(cwidth-lwidth)/2+"px"; login.style.top=(cheight-lheight)/2+"px"; mask.style.height=cheight+"px"; } //获取拖拽容器 var title=document.getElementById("title"); var isDraging=false; var mouseOffsetX; var mouseOffsetY; //鼠标按下事件 title.onmousedown=function(e){ var e=e||window.event; /*var el=e.srcElement; if(!el){ el=e.target;//兼容火狐 }*/ //鼠标相对于登录框的位置 mouseOffsetX=e.pageX-login.offsetLeft; mouseOffsetY=e.pageY-login.offsetTop; //鼠标摁下时为true isDraging=true; /*console.log(mouseOffsetY, mouseOffsetX)*/ } //鼠标移动事件 document.onmousemove=function(e){ var e=e||window.event; //鼠标移动时的坐标 var newMX=e.pageX; var newMY=e.pageY; //判断为true时可以拖拽 if(isDraging===true){ //登录框的偏移值=当前位置-鼠标到登录框的距离 var loginL=newMX-mouseOffsetX; var loginT=newMY-mouseOffsetY; //如果left top值超过边缘时就让他等于边缘 if(loginL<0){ loginL=0; }else if(loginL>(cwidth-lwidth)){ loginL=cwidth-lwidth; } if(loginT<0){ loginT=0; }else if(loginT>(cheight-lheight)){ loginT=cheight-lheight; } login.style.left=loginL+"px"; login.style.top=loginT+"px"; } } //鼠标弹起时设置为不可拖拽 document.onmouseup=function(){ isDraging=false; } //点击X关闭登录框和弹出层 var close=login.getElementsByClassName("close")[0]; close.onclick=function(){ document.body.removeChild(mask); document.body.removeChild(login); } } //点击登录弹出登录框和弹出层 window.onload=function(){ var btn=document.getElementById("btn"); btn.onclick=function(){ b(); } } |
-
上一个: VMware设置桥接上网的教程
相关文章
- js实现登录框鼠标拖拽效果 06-12
- js 漂亮登录框 11-22
- HTML简单购物数量小程序代码展示 10-31
- html canvas实现弹幕功能 10-31
- HTML中空格表示的意义 10-31
- html area标签解读 10-31