【JavaScript】实现拖拽功能并持久化

文章介绍了如何使用JavaScript实现网页元素的拖拽功能,同时利用cookie进行位置信息的存储,包括设置、获取和删除cookie的方法。
摘要由CSDN通过智能技术生成

为需要拖拽的元素添加 mousedown、mousemove和mouseup 事件监听器。 在 mousedown
事件处理函数中,记录⿏标按下时的位置,以及⿏标相对于元素的位置。 在 mousemove 事
件处理函数中,计算⿏标移动的距离,并更新元素的位置。 在 mouseup 事件处理函数中,移
除 mousemove 和 mouseup 事件监听器。

示例一:dom 元素拖拽

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background: pink;
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
</head>
<body>
<div id="box"></div>
<script>
    let manageCookie = {
        setCookie: function (name, value, date) {
            // expires 要求传入一个时间节点(默认规定传入一个天数)
            // let endDate = new Date()
            // endDate.setDate(endDate.getDate() + date)
            // document.cookie(`${name}=${value}; expires=${endDate};`)
            document.cookie = `${name}=${value}; max-age=${date};`
        },
        removeCookie: function (name) {
            this.setCookie(name, '', 0)
        },
        getCookie: function (name) {
            let cookies = document.cookie.split('; ')
            for (let i = 0; i < cookies.length; i++) {
                let item = cookies[i].split('=')
                if (item[0] === name) {
                    return item[1]
                }
            }
        },
    }

    // 拖拽
    let drag = {
        init: function (dom) {
            this.dom = dom
            this.bindEvent()
            let l = manageCookie.getCookie('newLeft')
            let t = manageCookie.getCookie('newTop')
            if (l) {
                this.dom.style.left = l + 'px'
            }
            if (t) {
                this.dom.style.top = t + 'px'
            }
        },
        bindEvent: function () {
            this.dom.onmousedown = this.mouseDown.bind(this)
        },
        mouseDown: function (e) {
            document.onmousemove = this.mouseMove.bind(this)
            document.onmouseup = this.mouseUp.bind(this)
            this.disX = e.clientX - this.dom.offsetLeft
            this.disY = e.clientY - this.dom.offsetTop
        },
        mouseMove: function (e) {
            this.newLeft = e.clientX - this.disX
            this.newTop = e.clientY - this.disY
            this.dom.style.left = this.newLeft + 'px'
            this.dom.style.top = this.newTop + 'px'
        },
        mouseUp: function () {
            document.onmousemove = null
            document.onmouseup = null
            // 鼠标抬起 存储位置信息
            manageCookie.setCookie('newLeft', this.newLeft, 1000)
            manageCookie.setCookie('newTop', this.newTop, 1000)
        },
    }
    drag.init(document.getElementById('box'))
</script>
</body>
</html>

image.png

示例二:侧边导航栏拖拽

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta
    http-equiv="X-UA-Compatible"
    content="IE=edge"
  >
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
  >
  <title>Document</title>
  <style>
    body {
      display: flex;
      margin: 0;
      min-height: 100vh;
    }

    .scalable {
      min-width: 200px;
      position: relative;
      background-color: #21252b;
    }

    .content img {
      display: block;
      width: 150px;
      user-select: none;
    }

    .main {
      flex: 1;
      background-color: #282c34;
    }

    .scalable .content {
      padding: 20px;
      padding-right: 34px;
    }

    .scalable .separator {
      width: 14px;
      height: 100%;
      background-color: #323842;
      box-shadow: 0 0 2px rgba(0, 0, 0, 0.35);
      position: absolute;
      top: 0;
      right: 0;
      cursor: col-resize;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .scalable .separator i {
      width: 2px;
      height: 14px;
      display: inline-block;
      background-color: #e9e9e9;
      margin: 0 1px;
    }
  </style>
</head>

<body>
  <div class="scalable">
    <div class="content">
      <img
        src="https://avatars.githubusercontent.com/u/61002730?v=4"
        alt=""
      >
    </div>
    <div class="separator">
      <i></i>
      <i></i>
    </div>
  </div>
  <div class="main"></div>
  <script>
    let startX, startWidth;
    let $ = tag => document.querySelector(tag)
    let getWidth = () => {
      return parseInt(window.getComputedStyle($('.scalable')).width)
    }
    let onDrag = (e) => {
      let newWidth = e.clientX - startX + startWidth;
      $('.scalable').style.width = newWidth + 'px'
    }
    let stopDrag = () => {
      document.documentElement.removeEventListener('mousemove', onDrag)
      document.documentElement.removeEventListener('mouseup', stopDrag)
    }
    let startDrag = (e) => {
      startX = e.clientX
      startWidth = getWidth()
      document.documentElement.addEventListener('mousemove', onDrag)
      document.documentElement.addEventListener('mouseup', stopDrag)
    }
    $('.separator').addEventListener('mousedown', startDrag)
  </script>
</body>

</html>

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小秀_heo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值