js实现模态框的拖拽效果

【js实现模态框的拖拽效果】本文实例为大家分享了js实现模态框拖拽效果的具体代码,供大家参考,具体内容如下
之前学习js遇到了这样的需求:
鼠标按下后,移动鼠标,模态框随鼠标移动,鼠标松开,模态框也不会随鼠标移动。<完整的代码在最后哦>
js实现模态框的拖拽效果
文章图片

分析思路:
1.点击弹出层,模态框和遮挡层就会显示出来。display:block
2.点击关闭按钮,模态框和遮挡层就会隐藏。display:none
js实现模态框的拖拽效果
文章图片

3.在页面中拖拽的步骤:鼠标按下并移动,之后松开鼠标
4.触发事件是鼠标按下mousedown,鼠标移动是mousemove,鼠标松开:mouseup
5.拖拽过程:鼠标移动过程中,获得最新的值赋值给模态框的left和top值,这样模态框就可以跟着鼠标走了
6.鼠标按下触发的时间源是最上面一行,也就是说,鼠标只有放在最上面一行,才能触发该事件。放在其他区域不会触发该事件。
7.鼠标的坐标减去鼠标在盒子内的坐标,才是模态框真正的位置。(因为模态框是可移动的,只有第一次才能拿到模态框的left和top,其他时候并不能直接拿到。所以采用‘鼠标的坐标 - 鼠标在模态框内的坐标’来计算模态框的位置)
js实现模态框的拖拽效果
文章图片

8.鼠标按下,我们要得到鼠标在盒子内的坐标
9.鼠标移动,就让模态框的坐标设置为:鼠标坐标 - 盒子坐标即可。注意移送事件要写到按下事件里面
10.鼠标松开,就停止拖拽,可以让鼠标移动事件解除
js实现模态框的拖拽效果
文章图片

代码实现:

模态框拖拽* {margin: 0; padding: 0; }#link {color: #000; text-decoration: none; border: 1px solid #000; }.login {width: 300px; height: 200px; background-color: antiquewhite; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 2; display: none; }.login-title {text-align: center; width: 100%; height: 40px; line-height: 40px; background-color: aqua; cursor: move; }.login-title span {display: block; height: 30px; width: 30px; background-color: antiquewhite; line-height: 30px; border-radius: 50%; position: absolute; top: -10px; right: -10px; font-size: 12px; }.login-title span a {text-decoration: none; color: #000; }.login-input-content {margin: 15px 20px 0; line-height: 30px; }.login-button {width: 200px; height: 20px; margin: 10px auto; border: 1px solid rgb(77, 73, 73); text-align: center; }.login-button a {text-decoration: none; color: #000; font-size: 14px; }#bg {display: none; background-color: #000; width: 100%; height: 100%; opacity: 0.3; z-index: -1; position: absolute; top: 0; left: 0; }点击,弹出登录框登录会员关闭会员登录

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读