目标功能
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
a {
position: absolute;
width: 100px;
height: 30px;
left: 50%;
transform: translateX(-50%);
font-size: 25px;
color: #000000;
line-height: 30px;
text-decoration: none;
}
.cover {
display: none;
position: fixed;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .3);
}
.login {
display: none;
position: absolute;
width: 500px;
height: 300px;
background-color: #ffffff;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.login .hd {
height: 60px;
line-height: 60px;
border-bottom: 1px solid #cccccc;
cursor: move;
}
.login .bd {
height: 240px;
line-height: 240px;
}
.login .close {
position: absolute;
top: -5%;
left: 95%;
width: 50px;
height: 50px;
background-color: #ffffff;
border-radius: 50%;
border: 1px solid #cccccc;
line-height: 50px;
cursor: pointer;
}
</style>
</head>
<body>
<a href="javascript:;">点我登陆</a>
<div class="cover"></div>
<div class="login">
<div class="hd">用户登陆,可以拖动</div>
<div class="bd">我是主体,不能拖动</div>
<div class="close">关闭</div>
</div>
<script>
var login = document.querySelector('.login');
var hd = document.querySelector('.hd');
hd.addEventListener('mousedown', function (e) {
var x = e.pageX - login.offsetLeft;
var y = e.pageY - login.offsetTop;
function move(e) {
login.style.left = e.pageX - x + 'px';
login.style.top = e.pageY - y + 'px';
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', function () {
document.removeEventListener('mousemove', move);
});
});
var a =document.querySelector('a');
var cover = document.querySelector('.cover');
var close = document.querySelector('.close');
a.addEventListener('click',function() {
login.style.display= 'block';
cover.style.display= 'block';
});
close.addEventListener('click',function() {
login.style.display= 'none';
cover.style.display= 'none';
login.style.left='50%';
login.style.top= '50%';
});
</script>
</body>
</html>