네이티브 js는 드래그 가능한 로그인 상자 효과를 구현합니다.
实现原理
1.onmousemove事件触发时不断更新鼠标的pageXY改变位置,
登陆框的偏移量=鼠标当前位置-鼠标到登录框边框的距离
2.onmousedown鼠标摁下时触发事件获取鼠标到登陆框的距离,再设置true允许拖拽
3.onmouseup 鼠标弹起设置false停止拖拽
4.登录框居中显示公式:(可视区域宽高-登录框宽高)/2
5.当浏览器窗口大小变化时触发事件window.onresize 再更新登陆框居中显示
代码中有详细的注释
完整代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>demo</title> <style> body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0;} body,button,input,select,textarea{font:12px/1.5 tahoma,arial,\5b8b\4f53;} h1,h2,h3,h4,h5,h6{font-size:100%;} address,cite,dfn,em,var{font-style:normal;} code,kbd,pre,samp{font-family:courier new,courier,monospace;} small{font-size:12px;} ul,ol{list-style:none;} a{text-decoration:none;} a:hover{text-decoration:underline;} sup{vertical-align:text-top;} sub{vertical-align:text-bottom;} legend{color:#000;} fieldset,img{border:0;} button,input,select,textarea{font-size:100%;} table{border-collapse:collapse;border-spacing:0;} .clear{clear: both;float: none;height: 0;overflow: hidden;} /*p{font-size: 100px;}*/ #btn{width: 80px; height: 40px; background: #3b7ae3; margin:0 auto; display: block; cursor: pointer; border-style: none; color: #fff; font-size: 16px;} #mask{ background: #000; opacity: 0.75; filter: alpha(opacity=75); height: 1000px; width: 100%; position: absolute; left: 0; top: 0; z-index: 1000; } #login{position: absolute; top: 100px; left: 100px; width: 400px; height: auto; border:1px solid #d5d5d5; z-index: 1001; } .title{position: relative;background-color: #f7f7f7; cursor: move; height: 50px; line-height: 50px; font-size: 16px; color: #333; padding-left:30px;} .close{position: absolute; top:0; right: 10px; color: #ccc;} .content{background: #fff; padding: 15px 20px;} .user{margin-bottom: 15px;} .password{margin-bottom: 15px;} .pt{display: block; height: 38px; padding-left: 15px; border: 1px solid #ddd; transition: .3s; font-size: 14px; color: #666; width: 343px; } .sm{display: block; height: 48px; border: 1px solid #ddd; transition: .3s; font-size: 16px; color: #666; width: 360px; background: #3b7ae3; color: #fff;} </style> </head> <body> <!-- <div id="mask"></div> --> <button id="btn" href="">登录</button> <!-- <div class="login" id="login"> <div class="title" id="title">登录百度账号<a href="#" class="close">x</a></div> <div class="content"> <div class="user"><input class="pt" type="input" value="手机/邮箱/用户名"></div> <div class="password"><input class="pt" type="input" value="密码"></div> <div class="submit"><input class="sm" type="submit" value="登录"></div> </div> </div> --> <script type="text/javascript"> 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='<div class="title" id="title">登录百度账号'+'<a href="#" class="close">x</a>'+'</div>'+ '<div class="content">'+'<div class="user">'+'<input class="pt" type="input" value="手机/邮箱/用户名">'+'</div>'+'<div class="password">'+'<input class="pt" type="input" value="密码">'+'</div>'+'<div class="submit">'+'<input class="sm" type="submit" value="登录">'+'</div>'+'</div>'; 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(); } } </script> </body> </html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持PHP中文网!
更多原生js实现可拖动的登录框效果相关文章请关注PHP中文网!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











기사는 JavaScript 라이브러리 작성, 게시 및 유지 관리, 계획, 개발, 테스트, 문서 및 홍보 전략에 중점을 둡니다.

이 기사는 브라우저에서 JavaScript 성능을 최적화하기위한 전략에 대해 설명하고 실행 시간을 줄이고 페이지로드 속도에 미치는 영향을 최소화하는 데 중점을 둡니다.

프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

이 기사는 브라우저 개발자 도구를 사용하여 효과적인 JavaScript 디버깅, 중단 점 설정, 콘솔 사용 및 성능 분석에 중점을 둡니다.

이 기사는 소스 맵을 사용하여 원래 코드에 다시 매핑하여 미니어링 된 JavaScript를 디버그하는 방법을 설명합니다. 소스 맵 활성화, 브레이크 포인트 설정 및 Chrome Devtools 및 Webpack과 같은 도구 사용에 대해 설명합니다.

이 기사는 Java의 컬렉션 프레임 워크의 효과적인 사용을 탐구합니다. 데이터 구조, 성능 요구 및 스레드 안전을 기반으로 적절한 컬렉션 (목록, 세트, 맵, 큐)을 선택하는 것을 강조합니다. 효율적인 수집 사용을 최적화합니다

엔트리 레벨 타입 스크립트 자습서를 마스터 한 후에는 TypeScript를 지원하고 JavaScript로 컴파일하는 IDE에서 자신의 코드를 작성할 수 있어야합니다. 이 튜토리얼은 TypeScript의 다양한 데이터 유형으로 뛰어납니다. JavaScript에는 NULL, UNDEFINED, BOOLEAN, 번호, 문자열, 기호 (ES6에 의해 소개 됨) 및 객체의 7 가지 데이터 유형이 있습니다. TypeScript는이 기반으로 더 많은 유형을 정의 하며이 튜토리얼은이 모든 튜토리얼을 자세히 다룹니다. 널 데이터 유형 JavaScript와 마찬가지로 Null in TypeScript

이 튜토리얼은 Chart.js를 사용하여 파이, 링 및 버블 차트를 만드는 방법을 설명합니다. 이전에는 차트 유형의 차트 유형을 배웠습니다. JS : 라인 차트 및 막대 차트 (자습서 2)와 레이더 차트 및 극지 지역 차트 (자습서 3)를 배웠습니다. 파이 및 링 차트를 만듭니다 파이 차트와 링 차트는 다른 부분으로 나뉘어 진 전체의 비율을 보여주는 데 이상적입니다. 예를 들어, 파이 차트는 사파리에서 남성 사자, 여성 사자 및 젊은 사자의 비율 또는 선거에서 다른 후보자가받는 투표율을 보여주는 데 사용될 수 있습니다. 파이 차트는 단일 매개 변수 또는 데이터 세트를 비교하는 데만 적합합니다. 파이 차트의 팬 각도는 데이터 포인트의 숫자 크기에 의존하기 때문에 원형 차트는 값이 0 인 엔티티를 그릴 수 없습니다. 이것은 비율이 0 인 모든 엔티티를 의미합니다
