原生JS实现窗口拖拽效果

按住鼠标按键,可以实现注册窗口自由拖拽效果;

<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .nav {
      height: 30px;
      background: #87cefa;
      line-height: 30px;
      padding-left: 30px;
    }

    .nav a {
      color: #fff;
      text-align: center;
      font-size: 14px;
      text-decoration: none;

    }

    .d-box {
      width: 400px;
      height: 300px;
      border: 5px solid #eee;
      box-shadow: 2px 2px 2px 2px #666;
      position: absolute;
      top: 50%;
      left: 50%;
      background-color: white;
      /* 不让文字被选中 */
      user-select: none;
      transform: translate(-50%, -50%);
    }

    .hd {
      width: 100%;
      height: 35px;
      background-color: #87cefa;
      border-bottom: 1px solid #369;
      line-height: 35px;
      color: white;
      cursor: move;
    }

    #box_close {
      float: right;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="nav">
    <a href="javascript:;" id="register">注册信息</a>
  </div>
  <div class="d-box" id="d_box">
    <div class="hd" id="drop">注册信息 (可以拖拽)
      <span id="box_close">【关闭】</span>
    </div>
    <div class="bd"></div>
  </div>

  <script>
    // 获取盒子
    var box = document.getElementById('d_box');
    // 获取盒子标题区块
    var drop = document.getElementById('drop');

    drop.onmousedown = function (e) {
      // 兼容性处理
      var e = e || window.event;

      // 当鼠标在盒子标题区域按下的时候,获取鼠标在盒子里面的下标
      // 鼠标在盒子的下标 = 鼠标在页面的的下标 - 盒子的偏移量;
      var x = e.pageX - box.offsetLeft;
      var y = e.pageY - box.offsetTop;

      console.log(x + " " + y);

      document.onmousemove = function (e) {
        // 兼容性处理
        var e = e || window.event;
        // 当鼠标在页面上移动的时候。求盒子的坐标
        // 盒子的坐标 = 鼠标当前在页面中的位置 - 鼠标在盒子中的位置
        var boxX = e.pageX - x;
        var boxY = e.pageY - y;
        box.style.left = boxX + "px";
        box.style.top = boxY + "px";

      }
    }

    // 当鼠标在页面文档中弹起,移除移动跟随
    document.onmouseup = function () {
      document.onmousemove = null;
    }

    // 点击关闭按钮,隐藏盒子
    var box_close = document.getElementById('box_close');
    box_close.onclick = function () {
      box.style.display = 'none';
    }
  </script>
</body>

</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是波哩个波

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值