模态框拖拽案例

目标功能

在这里插入图片描述

  • 实现登录框可由鼠标拖拽移动

代码实现

<!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;
      /* 开启固定定位,才能设置宽高为视口的100% */
      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;

      // 改变login的left和top值
      function move(e) {
        login.style.left = e.pageX - x + 'px';
        login.style.top = e.pageY - y + 'px';
      }

      // 为document添加鼠标移动事件,可以在整个页面范围拖动,而不是hd
      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>
发布了135 篇原创文章 · 获赞 0 · 访问量 3089

猜你喜欢

转载自blog.csdn.net/qq_35764106/article/details/105213068