实现的主要原理:(1)通过鼠标按下id="login_title"的区域,为页面注册鼠标移动事件 (2)通过鼠标事件的 .clientX, .clientY得到鼠标在屏幕中的距离屏幕左和上的偏移量 (3)用定位来实现单窗的位置改变从而实现弹窗的移动
HTML结构:
<!-- 弹窗按钮 -->
<div id="login_herder">点击,弹出登录框</div>
<!-- 整个窗口 -->
<div id="login">
<div id="login_title">
登录会员
<span>关闭</span>
</div>
<div class="login-input-content">
<div class="login-input">
<label>用户名</label>
<input type="text" placeholder="请输入用户名" name="info[username]" id="username" class="list-input">
</div>
<div class="login-input">
<label>登录密码:</label>
<input type="text" placeholder="请输入登录密码" name="info[password]" id="password" class="list-input">
</div>
</div>
<div id="login-btn">
登录会员
</div>
</div>
CSS的样式:
<style>
#login_herder {
color: #000000;
font-size: 24px;
line-height: 30px;
width: 192px;
height: 31px;
position: absolute;
left: 50%;
margin-left: -96px;
cursor: pointer;
}
#login {
position: absolute;
width: 512px;
height: 282px;
left: 50%;
margin-left: -256px;
margin-top: 140px;
border: #ebebeb solid 1px;
box-shadow: 0 0 20px #ddd;
display: none;
}
#login_title {
width: 100%;
height: 40px;
text-align: center;
font-size: 18px;
height: 40px;
margin-top: 10px;
cursor: move;
}
#login_title>span {
height: 42px;
width: 42px;
position: absolute;
right: -20px;
top: -20px;
border: #ebebeb solid 1px;
border-radius: 50%;
font-size: 12px;
line-height: 42px;
background-color: #fff;
}
#login>.login-input-content>.login-input {
margin-top: 20px;
overflow: hidden;
/* overflow作用子元素加了浮动导致高度坍陷 */
}
#login>.login-input-content>.login-input label {
float: left;
width: 90px;
padding-right: 10px;
text-align: right;
line-height: 35px;
height: 35px;
font-size: 14px;
}
#login>.login-input-content>.login-input input {
float: left;
line-height: 35px;
height: 35px;
width: 350px;
border: #ebebeb 1px solid;
text-indent: 5px;
}
#login-btn {
width: 258px;
height: 42px;
line-height: 42px;
text-align: center;
margin: 30px auto 0 auto;
border: #ebebeb 1px solid;
font-size: 14px;
}
</style>
JS逻辑部分:
<script>
//弹出登录框按钮
var login_herder = document.getElementById("login_herder");
//整个登录框
var login = document.getElementById("login");
//登录框文字部分,手机按上去拖到区域
var login_title = document.getElementById("login_title");
login_herder.onclick = function() {
login.style.display = "block"
}
login_title.onmousedown = function(e) {
//spaceX鼠标在登录弹窗中,距离左边框的左偏移量
var spaceX = e.clientX - login.offsetLeft;
//spaceY鼠标在登录弹窗中,距离上边框的上偏移量
var spaceY = e.clientY - login.offsetTop;
//按下login_title区域,为整个网页文档注册鼠标移动事件
document.onmousemove = function(e) {
//256和140分别是margin-left和margin-top。目的为了抵消掉margin
var x = e.clientX - spaceX + 256;
var y = e.clientY - spaceY - 140;
login.style.left = x + "px";
login.style.top = y + "px";
}
}
//松开下login_title区域,为整个网页文档解绑鼠标移动事件
login_title.onmouseup = function() {
document.onmousemove = null;
}
</script>
得到x和y的逻辑图: