案例-鼠标拖动弹出框
需求:
- 打开网页刚开始是空白页面,仅有一句提示:点击弹出登录框
- 用户鼠标点击任意位置,登录框弹出
- 用户点击登录框顶部(登录会员一行位置)时,可拖动整个登录框,点其他位置不可拖动
思路:
- 登录框开始是隐藏状态,用户点击任意位置,登录框出现,diaplay:none和display:block两者切换
- 鼠标拖动登录框时,鼠标指针位置相对于登录框是不变的,这点可用于计算
- 开关思想
结构:
<h1>点击弹出登录框</h1>
<div class="login">
<h3>登录会员</h3>
<form action="">
<div class="row">
<div class="labels fl">
<label for="user">用户名:</label>
</div>
<div class="input fr">
<input type="text" id="user" placeholder="请输入用户名">
</div>
</div>
<div class="row">
<div class="labels fl">
<label for="pwd">登录密码:</label>
</div>
<div class="input fr">
<input type="password" id="pwd" placeholder="请输入登录密码">
</div>
</div>
<input type="submit" class="btn" value="登录会员">
</form>
</div>
样式:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #fafafa;
}
.fl {
float: left;
}
.fr {
float: right;
}
h1 {
text-align: center;
font-weight: 400;
}
.login {
position: absolute;
top: 200px;
left: 200px;
width: 500px;
height: 250px;
background-color: #fff;
box-shadow: 2px 2px 10px 4px #eee;
display: none;
}
h3 {
width: 100%;
height: 60px;
line-height: 60px;
text-align: center;
font-weight: 400;
cursor: move;
}
.row {
width: 100%;
height: 60px;
line-height: 60px;
}
.labels {
width: 20%;
text-align: right;
}
.input {
width: 80%;
text-align: left;
}
input {
width: 330px;
height: 40px;
margin-left: 20px;
border: 1px solid #eee;
padding-left: 10px;
outline: none;
}
input[type="submit"] {
width: 200px;
height: 40px;
background-color: #fff;
margin: 15px 150px;
padding: 0;
cursor: pointer;
}
.show {
display: block;
}
js:
var h3 = document.querySelector('h3');
var login = document.querySelector('.login')
var inLeft;
var inTop;
var flag = false;
document.addEventListener('click', function() {
login.classList.add('show');
});
h3.addEventListener('mousedown', function (e) {
inLeft = e.pageX - login.offsetLeft;
inTop = e.pageY - login.offsetTop;
flag = true;
});
document.addEventListener('mousemove', function (e) {
if (flag) {
var left = e.pageX - inLeft;
var top = e.pageY - inTop;
login.style.left = `${left}px`;
login.style.top = `${top}px`;
}
});
h3.addEventListener('mouseup', function () {
flag = false;
});