JavaScript----点击按钮弹出登录框以及拖拽效果练习
目录一、练习要求:二、效果图三、需求分析:四、拖拽原理: 五、代码如下:CSS部分htmlJS 六、演示效果:点击登录注册,弹出登陆窗口,且该窗口可以关闭,可以拖拽,在弹出窗口的同时,整个页面变成灰色半透明。如下:图1是起始页面,图2是点击“点击,弹出登陆框”按钮后页面,图3是登陆框自由拖动后页面。图1图2 图31.让整个页面变成灰色半透明,需要使用div对整个屏幕进行覆盖,这个div称为覆盖层
·
目录
一、练习要求:
点击登录注册,弹出登陆窗口,且该窗口可以关闭,可以拖拽,在弹出窗口的同时,整个页面变成灰色半透明。
二、效果图
如下:图1是起始页面,图2是点击“点击,弹出登陆框”按钮后页面,图3是登陆框自由拖动后页面。
图1
图2
图3
三、需求分析:
1.让整个页面变成灰色半透明,需要使用div对整个屏幕进行覆盖,这个div称为覆盖层。
2.点击按钮的时候,弹出登陆窗口和覆盖层,注意,登陆窗口的层级(z-index)应该最高,覆盖层其次。
3.点击关闭按钮的时候,隐藏登陆窗口和覆盖层。
4.实现登陆窗口的拖拽。
四、拖拽原理:
1、mousedown 鼠标按压获取鼠标在登录框的宽度。
2、mousemove 鼠标移动的时获取最新的pageX减去鼠标在登录框的X距离,就是模态框的left与top值。
3、mouseup 鼠标松开时,移除mousemove 事件
五、代码如下:
CSS部分
* {
padding: 0px;
margin: 0px;
}
li {
list-style: none;
}
a {
text-decoration: none;
}
/* 遮盖层 */
.bg {
width: 100%;
height: 100%;
position: fixed;
top: 0px;
left: 0px;
background: rgb(0, 0, 0, .4);
z-index: 9998;
display: none;
}
/* 登录弹框 */
.login {
width: 600px;
height: 300px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
background: #fff;
display: none;
}
/* 登录框标题 */
.title {
height: 45px;
line-height: 45px;
text-align: center;
border-bottom: 1px solid #DCDCDC;
position: relative;
cursor: move;
}
/* 登录框表单 */
.content p {
text-align: center;
line-height: 45px;
}
/* 关闭登录弹框 */
.title a {
display: block;
position: fixed;
top: 2px;
right: 5px;
z-index: 9999;
}
html
<!-- 制作登录框 -->
<a href="javascript:;" id="loginA">注册/登录</a>
<!-- 登录弹框 -->
<div class="login">
<!-- 登录框标题 -->
<div class="title">
用户登录 <a href="javascript:;" id="close">关闭</a>
</div>
<!-- 登录框表单 -->
<div class="content">
<p> 用户名:<input type="text" value="" /></p>
<p> 密 码:<input type="password" value="" /></p>
<p> <input type="button" value="提交" /></p>
</div>
</div>
<!-- 遮盖层 -->
<div class="bg"></div>
JS
<script>
// 获取元素
var link = document.querySelector('#loginA');
var login = document.querySelector(".login");
var bg = document.querySelector(".bg");
var closeBtn = document.querySelector("#close");
var title = document.querySelector(".title");
// 点击注册/登录,显示遮盖层bg、登录窗口login
link.addEventListener("click", function () {
bg.style.display = 'block';
login.style.display = 'block';
})
// 关闭登录框 隐藏遮盖层bg 、登录窗口login
closeBtn.addEventListener("click", function () {
bg.style.display = 'none';
login.style.display = 'none';
})
//鼠标拖拽功能
// (1) 当我们鼠标按下, 就获得鼠标在盒子内的坐标
login.addEventListener("mousedown", function (e) {
var x = e.pageX - login.offsetLeft;
var y = e.pageY - login.offsetTop;
//计算鼠标移动时 登陆框需要移动的距离
document.addEventListener("mousemove", move)
function move(e) {
login.style.left = e.pageX - x + "px";
login.style.top = e.pageY - y + "px";
}
//清除 mousemove移动事件
document.addEventListener("mouseup", function () {
document.removeEventListener("mousemove", move)
})
})
</script>
六、演示效果:
更多推荐
已为社区贡献3条内容
所有评论(0)