html5 拖拽及用 js 实现拖拽功能的示例代码


Posted in HTML / CSS onOctober 23, 2020

1. HTML5 拖拽

1.1 相关知识

拖拽元素:可以为元素添加 draggable="true"来让元素能够被拖拽。

拖拽元素的事件监听:(应用于拖拽元素)

  • ondragstart当拖拽开始时调用
  • ondragleave 当鼠标离开拖拽元素时调用
  • ondragend 当拖拽结束时调用
  • ondrag 整个拖拽过程都会调用

目标元素:把元素A拖拽到元素B里,那么元素B就是目标元素。页面中任何一个元素都可以成为目标元素。

目标元素的事件监听:(应用于目标元素)

  • ondragenter 当拖拽元素进入时调用
  • ondragover 当拖拽元素停留在目标元素上时,就会连续一直触发(不管拖拽元素此时是移动还是不动的状态)
  • ondrop 当在目标元素上松开鼠标时调用
  • ondragleave 当鼠标离开目标元素时调用

如果想让拖拽元素在目标元素里做点事情,就必须要在 ondragover() 里加event.preventDefault()这一行代码。

1.2 拖拽基础

<!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>
            .box {
                width: 200px;
                height: 200px;
                background: green;
            }
            .box2 {
                position: relative;
                left: 300px;
                top: 50px;
                width: 300px;
                height: 300px;
                background: red;
            }
        </style>
    </head>
    <body>
        <div class="box" draggable="true"></div>
        <div class="box2"></div>
        <script>
            // HTML5 拖拽
            // 应用于拖拽元素
            var box = document.querySelector('.box')
            box.ondragstart = function () {
                console.log('拖拽开始')
            }
            box.ondragleave = function () {
                console.log('鼠标离开元素')
            }
            box.ondragend = function () {
                console.log('拖拽结束')
            }
            // box.ondrag = function () {
            //     console.log('在拖拽');
            // }

            // 应用于目标元素(想把 box 拖拽进去的地方)
            var box2 = document.querySelector('.box2')
            box2.ondragenter = function () {
                console.log('进来了')
            }
            box2.ondragleave = function () {
                console.log('离开了')
            }

            // 当拖拽元素在 目标元素上时,连续触发
            box2.ondragover = function (e) {
                // 如果想让拖拽元素在目标元素里做点事情,就必须要在 ondragover() 里加event.preventDefault()这一行代码。
                e.preventDefault()
                console.log('over')
            }
            box2.ondrop = function () {
                console.log('松开鼠标了')
            }
        </script>
    </body>
</html>

1.3 将 A 在 B、C 之间拖拽

<!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>
            .box-b {
                width: 250px;
                height: 250px;
                background: green;
            }
            .cell-a {
                float: left;
                width: 50px;
                height: 50px;
                margin: 5px;
                text-align: center;
                line-height: 50px;
                border-radius: 50%;
                background: red;
            }
            .box-c {
                width: 200px;
                height: 200px;
                margin-top: 10px;
                background: skyblue;
            }
        </style>
    </head>
    <body>
        <p>boxB</p>
        <div class="box-b">
            <div class="cell-a" draggable="true">1</div>
            <div class="cell-a" draggable="true">2</div>
            <div class="cell-a" draggable="true">3</div>
            <div class="cell-a" draggable="true">4</div>
            <div class="cell-a" draggable="true">5</div>
        </div>
        <p>boxC</p>
        <div class="box-c"></div>
        <script>
            var cellA = document.querySelectorAll('.cell-a')
            var boxB = document.querySelector('.box-b')
            var boxC = document.querySelector('.box-c')
            var temp = null

            cellA.forEach((cell, index) => {
                // 从 boxB 拖拽到 boxC
                cell.ondragstart = function () {
                    // 保持当前拖拽的元素
                    temp = this
                }
                cell.ondragend = function () {
                    temp = null
                }
                boxC.ondragover = function (e) {
                    e.preventDefault()
                }
                boxC.ondragenter = function () {
                    this.appendChild(temp)
                }

                // 从 boxC 拖拽到 boxB
                boxB.ondragover = function (e) {
                    e.preventDefault()
                }
                boxB.ondragenter = function () {
                    this.appendChild(temp)
                }
            })
        </script>
    </body>
</html>

效果展示

html5 拖拽及用 js 实现拖拽功能的示例代码

2. 用 js 实现拖拽

2.1 js 简单拖拽

按下鼠标进行简单的拖拽。

<!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>
            #box {
                position: absolute;
                width: 200px;
                height: 200px;
                background: green;
            }
        </style>
        <script>
            window.onload = function () {
                var box = document.getElementById('box')
                var disX = 0
                var disY = 0

                box.onmousedown = function (e) {
                    var e = e || window.event
                    disX = e.clientX - this.offsetLeft
                    disY = e.clientY - this.offsetTop
                    box.onmousemove = function (e) {
                        var e = e || window.event
                        box.style.left = e.clientX - disX + 'px'
                        box.style.top = e.clientY - disY + 'px'
                    }
                    box.onmouseup = function (e) {
                        console.log('end')
                        this.onmousemove = null
                    }
                    return false
                }
            }
        </script>
    </head>
    <body>
        <div id="box"></div>
    </body>
</html>

效果展示

html5 拖拽及用 js 实现拖拽功能的示例代码

2.2 带效果的拖拽

<!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>
            .box {
                position: absolute;
                width: 200px;
                height: 200px;
                background: skyblue;
            }
            .box1 {
                position: absolute;
                border: 1px dashed black;
                opacity: 0.5;
            }
            .way-box {
                position: absolute;
                bottom: 30px;
                right: 30px;
                /* 无法选中 */
                -moz-user-select: none; /* 火狐 */
                -webkit-user-select: none; /* 谷歌 */
                -ms-user-select: none; /* IE */
                user-select: none;
            }
        </style>
        <script>
            window.onload = function () {
                ;(function () {
                    var box = document.querySelector('.box')
                    var disX, disY, temp
                    var body = document.querySelector('body')
                    var way1 = document.querySelector('#way1')
                    var way2 = document.querySelector('#way2')

                    box.onmousedown = function (e) {
                        var e = e || window.event // 兼容性写法
                        disX = e.clientX - this.offsetLeft
                        disY = e.clientY - this.offsetTop

                        temp = document.createElement('div')
                        body.appendChild(temp)
                        temp.classList.add('box')
                        temp.classList.add('box1')
                        // 移动后位置会变,temp 的位置应该与 box 位置重合
                        temp.style.left = e.clientX - disX + 'px' // 记得加单位!
                        temp.style.top = e.clientY - disY + 'px'

                        temp.onmousemove = function (e) {
                            var e = e || window.event
                            temp.style.left = e.clientX - disX + 'px' // 记得加单位!
                            temp.style.top = e.clientY - disY + 'px'
                        }
                        temp.onmouseup = function (e) {
                            console.log('end')
                            this.onmousemove = null
                            // 1 则默认不发生实际移动
                            if (way2.checked) {
                                box.style.left = e.clientX - disX + 'px'
                                box.style.top = e.clientY - disY + 'px'
                            }
                            temp.style.display = 'none'
                            this.onmouseup = null
                        }
                    }
                })()
            }
        </script>
    </head>
    <body>
        <div class="box"></div>
        <div class="way-box">
            <p>请选择拖拽的方式</p>
            <input type="radio" id="way1" name="way" checked />
            <label for="way1">1</label>
            <input type="radio" id="way2" name="way" />
            <label for="way2">2</label>
        </div>
    </body>
</html>

效果展示

html5 拖拽及用 js 实现拖拽功能的示例代码

有时会卡顿,未解决…

到此这篇关于html5 拖拽及用 js 实现拖拽的文章就介绍到这了,更多相关html5 拖拽内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章,希望大家以后多多支持三水点靠木!

HTML / CSS 相关文章推荐
纯CSS3实现表单验证效果(非常不错)
Jan 18 HTML / CSS
CSS3 animation实现简易幻灯片轮播特效
Sep 27 HTML / CSS
CSS3 实现footer 固定在底部(无论页面多高始终在底部)
Oct 15 HTML / CSS
CSS 说明横向进度条最后显示文字的实现代码
Nov 10 HTML / CSS
CSS3 按钮边框动画的实现
Nov 12 HTML / CSS
12个不为大家熟知的HTML5设计小技巧
Jun 02 HTML / CSS
使用HTML5 Geolocation实现一个距离追踪器
Apr 09 HTML / CSS
HTML5给汉字加拼音收起展开组件的实现代码
Apr 08 HTML / CSS
AmazeUI 点击元素显示全屏的实现
Aug 25 HTML / CSS
HTML5中 rem适配方案与 viewport 适配问题详解
Apr 27 HTML / CSS
css实现两栏布局,左侧固定宽,右侧自适应的多种方法
Aug 07 HTML / CSS
使用 CSS 轻松实现一些高频出现的奇形怪状按钮
Dec 06 HTML / CSS
html5小程序飞入购物车(抛物线绘制运动轨迹点)
Oct 19 #HTML / CSS
app内嵌H5 webview 本地缓存问题的解决
Oct 19 #HTML / CSS
使用HTML5做的导航条详细步骤
Oct 19 #HTML / CSS
利用Node实现HTML5离线存储的方法
Oct 16 #HTML / CSS
HTML+CSS+JavaScript实现图片3D展览的示例代码
Oct 12 #HTML / CSS
HTML5逐步分析实现拖放功能的方法
Sep 30 #HTML / CSS
移动端HTML5 input常见问题(小结)
Sep 28 #HTML / CSS
You might like
调试一段PHP程序时遇到的三个问题
2012/01/17 PHP
PHP类的自动加载机制实现方法分析
2019/01/10 PHP
一页面多XMLHttpRequest对象
2007/01/22 Javascript
Javascript技巧之不要用for in语句对数组进行遍历
2010/10/20 Javascript
IE6下focus与blur错乱的解决方案
2011/07/31 Javascript
Jquery实现侧边栏跟随滚动条固定(兼容IE6)
2014/04/02 Javascript
javascript操作excel生成报表示例
2014/05/08 Javascript
javascript常用函数归纳整理
2014/10/31 Javascript
JS实现让访问者自助选择网页文字颜色的方法
2015/02/24 Javascript
jQuery焦点图插件SaySlide
2015/12/21 Javascript
js删除局部变量的实现方法
2016/06/25 Javascript
jquery Easyui Datagrid实现批量操作(编辑,删除,添加)
2017/02/20 Javascript
jQuery中clone()函数实现表单中增加和减少输入项
2017/05/13 jQuery
JavaScript中import用法总结
2019/01/20 Javascript
基于vue-cli3创建libs库的实现方法
2019/12/04 Javascript
vue实现购物车的小练习
2020/12/21 Vue.js
[01:46]辉夜杯—打造中国DOTA新格局
2015/12/25 DOTA
Python实现变量数值交换及判断数组是否含有某个元素的方法
2017/09/18 Python
python使用PyCharm进行远程开发和调试
2017/11/02 Python
python递归实现快速排序
2018/08/18 Python
浅谈Python中的bs4基础
2018/10/21 Python
Django框架封装外部函数示例
2019/05/28 Python
Python将二维列表list的数据输出(TXT,Excel)
2020/04/23 Python
Python实现清理微信僵尸粉功能示例【基于itchat模块】
2020/05/29 Python
Python如何操作docker redis过程解析
2020/08/10 Python
详解python内置模块urllib
2020/09/09 Python
NHL官方在线商店:Shop.NHL.com
2020/05/01 全球购物
岗位竞聘演讲稿
2014/01/10 职场文书
酒店七夕情人节活动策划方案
2014/08/24 职场文书
音乐之声音乐广播稿
2014/09/10 职场文书
2014年卫生监督工作总结
2014/12/09 职场文书
被告代理词范文
2015/05/25 职场文书
党性教育心得体会(共6篇)
2016/01/21 职场文书
浅谈PostgreSQL表分区的三种方式
2021/06/29 PostgreSQL
解决Laravel使用验证时跳转到首页的问题
2021/11/17 PHP
Pycharm远程调试和MySQL数据库授权问题
2022/03/18 MySQL