<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.button{
width: 100px;
height: 40px;
border-radius: 5px;
background: lightblue;
text-align: center;
line-height: 40px;
margin: 0 auto;
}
.wrap{
position: absolute;
top: 0;
left: 0;
background: rgba(0,0,0,0.5);
}
.box{
width: 250px;
height: 100px;
border-radius: 10px;
background: black;
position: fixed;
cursor: move;
visibility: hidden;
}
</style>
</head>
<body>
<div class="button">点击</div>
<div class="wrap">
<div class="box"></div>
</div>
<script>
main(".wrap",".box",".button");
function getDom(dom){
return document.querySelectorAll(dom);
}
function main(wrap,box,button){
var wrap=getDom(wrap);
var button=getDom(button);
var box=getDom(box);
var windowWidth=document.documentElement.clientWidth;//用于获取整个页面的宽
var windowHeight=document.documentElement.clientHeight;//用于获取整个页面的高
button[0].onclick=function(){
console.log(document.body.offsetHeight);
wrap[0].style.width=windowWidth+"px";
wrap[0].style.height=windowHeight+"px";//给遮罩层加上宽高,使其显现出来
var boxHeight=box[0].offsetHeight;
var boxWidth=box[0].offsetWidth;
box[0].style.visibility="visible";//拖拽元素显现出来
box[0].style.left=(windowWidth-boxWidth)/2+"px";
box[0].style.top=(windowHeight-boxHeight)/2+"px";//将拖拽元素居中
delWrap(wrap,button,box);
drag(wrap,box,button);
}
}
function delWrap(wrap,button,box){//点击遮罩层消失
wrap[0].onclick=function(e){
if(this==e.target){
wrap[0].style.visibility="hidden";
box[0].style.visibility="hidden";
}
}
}
function drag(wrap,box,button){
box[0].onmousedown=function(e){
var preX=e.clientX;
var preY=e.clientY;
var initLeft=box[0].style.left;//存储点击前的left,top初始值
var initTop=box[0].style.top;
(function(preX,preY,initLeft,initTop){
box[0].onmousemove=function(event){
var currentX=event.clientX;//获取移动的X,Y
var currentY=event.clientY;
box[0].style.left=(currentX-preX)+parseInt(initLeft)+"px";
box[0].style.top=(currentY-preY)+parseInt(initTop)+"px";
}
})(preX,preY,initLeft,initTop);//利用闭包将函数外部参数传入内部
box[0].onmouseup=function(){
box[0].onmousemove=null;//一旦松开,则解除move事件
}
}
}
</script>
</body>
</html>
遮罩层显示,框的移动拖拽功能
最新推荐文章于 2021-05-31 00:26:40 发布