前端HTML5元素实现拖拽:drag、drop

程序开发前端后端区分|前端页面开发要求|前端开发面试项目展示

HTML5中实现拖放操作,至少经过如下步骤
1)设置被拖放对象元素的draggable属性设置为true
2)编写与拖放有关的事件处理代码
[table=50%]
[tr][td] 事件[/td][td]产生事件的元素
[/td][td] 描述[/td][/tr]
[tr][td] dragstart[/td][td] 被拖拽物体[/td][td]开始拖放[/td][/tr]
[tr][td] dragenter[/td][td] 被拖拽物体开始进入区域
[/td][td] 进入范围[/td][/tr]
[tr][td] dragover[/td][td] 拖放过程中鼠标经过的元素(包括目标对象)[/td][td] 正在元素上[/td][/tr]
[tr][td] dragleave[/td][td] 拖放离开时鼠标经过的元素(包括目标对象)[/td][td] 离开范围[/td][/tr]
[tr][td] drop[/td][td] 目标对象[/td][td]被拖拽物体放下
[/td][/tr]
[tr][td] dragend[/td][td]被拖拽物体
[/td][td] 拖放结束[/td][/tr]
[/table]
事件发生的顺序: dragstart -> dragenter -> dragover ->dragleave ->drop ->dragend

如果分为两组来看:

[table=50%]
[tr][td] 被拖拽元素 (发生的事件)
[/td][td] 要进入的目标元素(发生的事件)[/td][/tr]
[tr][td] dragstart[/td][td] dragenter[/td][/tr]
[tr][td] dragend[/td][td] dragover[/td][/tr]
[tr][td] [/td][td] dragleve[/td][/tr]
[tr][td] [/td][td] drop[/td][/tr]
[/table]

ps.教程里的preventDefault() 看上去好像无效,其实应该增加阻止冒泡就不会打开图片了。

  1. 第一个小例子:做了一个删除icon 的demo
    代码片段 1
<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
    <title>excel前端程序开发</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            background-color: black;
        }
        .wrapper {
            width: 580px;
            margin: 0px auto;
            margin-top: 80px;
        }
        ul {
            list-style: none;
        }
        li {
            float: left;
            margin-right: 20px;
        }
        img {
            border-radius: 12px;
            width: 100px;
            height: 100px;
        }
        .rubbish {
            position: absolute;
            bottom: 80px;
            background: url(“data/attachment/album/201407/21/220839emsyf6bty8sfgrxf.png”) no-repeat;
            width: 128px;
            height: 128px;
            left: 50%;
            margin-left: -64px;
        }
    </style>
</head>
<body>
    <div class=”wrapper”>
        <ul>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/78/60/786031289/mzl.kcoxjsrs.png1.jpg” id=”1″ />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/88/61/886104377/mzl.dgltpgis.png1.jpg” id=”2″ />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/84/1/840146800/mzl.eiohimmz.png1.jpg” id=”3″ />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/83/59/835969177/mzl.aiikkslk.png1.jpg” id=”4″ />
            </li>
        </ul>
    </div>
    <div class=”rubbish” id=”rubbish”></div>
    <script>
        var iconarr = document.getElementsByTagName(“li”); //icon数组
        var rubbishbin = document.getElementById(“rubbish”);
        for (var i = 0; i < iconarr.length; i++) {
            iconarr[i].ondragstart = function (ev) {
                /*拖拽开始(被拖拽元素) ondragstart 不可以写preventDefault事件*/
                ev.dataTransfer.setData(“text”, ev.target.id); //存储拖拽元素的id*/
            }
        }
        rubbishbin.ondragover = function (ev) {
            /*拖拽元素进入目标元素头上,不可少*/
            ev.preventDefault();
        }
        rubbishbin.ondrop = function (ev) {
            /*拖拽元素进入目标元素头上,同时鼠标松开的时候*/
            ev.preventDefault();
            if (window.addEventListener) {
                ev.stopPropagation();
            } else if (window.attachEvent) {
                ev.cancelBubble = true;
            }
            var ul = document.getElementsByTagName(“ul”)[0];
            var node = document.getElementById(ev.dataTransfer.getData(“text”)).parentNode; //拖拽的是img 移除的是Li
            ul.removeChild(node);
            rubbishbin.style.background = “url(‘data/attachment/album/201407/21/220926qem3c3dsu53u8sha.png’) no-repeat”;
        }
    </script>
</body>
</html>
<script>
</script>

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Demo</title>
<style>
html,body{width:100%;height:100%;background-color:black;}
.wrapper{ width:580px;margin:0px auto;margin-top:80px;}
ul{list-style:none;}
li{float:left;margin-right:20px;}
img{border-radius:12px;width:100px;height:100px;}
.rubbish{position:absolute;bottom:80px;background:url(“empty.png”) no-repeat;width:128px;height:128px;left:50%;margin-left:-64px;}
</style>
</head>
<body>
<div class=”wrapper”>
<ul>
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/78/60/786031289/mzl.kcoxjsrs.png1.jpg&quot; id=”1″/></li>
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/88/61/886104377/mzl.dgltpgis.png1.jpg&quot; id=”2″/></li>
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/84/1/840146800/mzl.eiohimmz.png1.jpg&quot; id=”3″/></li>
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/83/59/835969177/mzl.aiikkslk.png1.jpg&quot; id=”4″/></li>
</ul>
</div>
<div class=”rubbish” id=”rubbish”></div>
<script>
var iconarr = document.getElementsByTagName(“li”);//icon数组
var rubbishbin = document.getElementById(“rubbish”);
for( var i=0;i<iconarr.length;i++ ){
iconarr[i].ondragstart = function(ev){
/拖拽开始(被拖拽元素) ondragstart 不可以写preventDefault事件/
ev.dataTransfer.setData(“text”,ev.target.id);//存储拖拽元素的id/
}
}
rubbishbin.ondragover = function(ev){
/
拖拽元素进入目标元素头上,不可少/
ev.preventDefault();
}
rubbishbin.ondrop = function(ev){
/
拖拽元素进入目标元素头上,同时鼠标松开的时候*/
ev.preventDefault();
if(window.addEventListener){
ev.stopPropagation();
}else if(window.attachEvent){
ev.cancelBubble=true;
}
var ul = document.getElementsByTagName(“ul”)[0];
var node = document.getElementById(ev.dataTransfer.getData(“text”)).parentNode;//拖拽的是img 移除的是Li
ul.removeChild(node);
rubbishbin.style.background=”url(full.png) no-repeat”;
}
</script>
</body>
</html>
<script>
</script>

  1. 利用drag & drop 拖拽物体更换位置
    代码片段 2
<!DOCTYPE HTML>
<html>
<head>
    <meta charset=”utf-8″ />
    <title>前端h5游戏开发工具</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            background-color: black;
        }
        .wrapper {
            width: 500px;
            margin: 0px auto;
            margin-top: 80px;
        }
        ul {
            list-style: none;
            width: 500px;
        }
        li {
            float: left;
            margin: 0px 20px 20px 0px;
            position: relative;
            width: 132px;
            height: 132px;
        }
        img {
            border-radius: 12px;
            width: 100px;
            height: 100px;
            position: relative;
            -moz-user-select: none;
            cursor: move;
        }
        .rubbish {
            position: absolute;
            bottom: 80px;
            background: url(“empty.png”) no-repeat;
            width: 128px;
            height: 128px;
            left: 50%;
            margin-left: -64px;
        }
        .hover {
            border: 3px dashed #fff;
        }
        .zIndex {
            transform: scale(0.8, 0.8);
            -moz-transform: scale(0.8, 0.8);
            -webkit-transform: scale(0.8, 0.8);
            -ms-transform: scale(0.8, 0.8);
            -o-transform: scale(0.8, 0.8);
            transition: transform .2s ease-in;
            -moz-transition: -moz-transform .2s ease-in;
            -o-transition: -o-transform .2s ease-in;
        }
    </style>
</head>
<body>
    <div class=”wrapper”>
        <ul>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/78/60/786031289/mzl.kcoxjsrs.png1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/88/61/886104377/mzl.dgltpgis.png1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/84/1/840146800/mzl.eiohimmz.png1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/83/59/835969177/mzl.aiikkslk.png1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/28/17/281796108/mzl.oyxfxpvw.png1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/87/85/878549709/mzl.swnecgkk.png1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/78/70/787063884/mzl.pmfectba.jpg1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/87/18/871809581/mzl.fbyoqfjw.png1.jpg” />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/66/93/669390657/mzl.ekoptmtx.png1.jpg” />
            </li>
        </ul>
    </div>
    <script>
        var imgarrs = document.querySelectorAll(“img”);
        var dragnow = null; //目前被拽着的物体
        for (var i = 0; i < imgarrs.length; i++) {
            addHandler(imgarrs[i], ‘dragstart’, dragstart);
            addHandler(imgarrs[i], ‘dragenter’, dragenter);
            addHandler(imgarrs[i], ‘dragover’, dragover);
            addHandler(imgarrs[i], ‘dragleave’, dragleave);
            addHandler(imgarrs[i], ‘drop’, drop);
            addHandler(imgarrs[i], ‘dragend’, dragend);
        }
        function addHandler(node, type, handler) {
            if (window.addEventListener) {
                node.addEventListener(type, handler, false);
            } else if (window.attachEvent) {
                node.attachEvent(‘on’ + type, handler);
            }
        }
        function dragstart(e) { //被拖拽元素
            if (typeof e.target.style.opacity != ‘undefined’) {
                e.target.style.opacity = ‘0.4’;
            } else {
                e.target.style.filter = “alpha(opacity=40)”;
            }
            addClass(e.target, “zIndex”);
            e.dataTransfer.setData(“text”, e.target.src); //存储图片的src
            dragnow = e.target; //目前被拽的物体
        }
        function dragover(e) { //拖拽目标身上的效果
            e.preventDefault();
            e.dataTransfer.dropEffect = ‘move’;
        }
        function dragenter(e) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            if (typeof e.target.classList != ‘undefined’) {
                e.target.classList.add(‘hover’);
            } else {
                addClass(e.target, “hover”);
            }
        }
        function dragleave(e) {
            removeClass(e.target, “hover”);
        }
        function drop(e) {
            var src = e.dataTransfer.getData(“text”); //获取src
            e.preventDefault();
            if (e.stopPropagation) {
                e.stopPropagation();
            } else if (e.attachEvent) {
                e.cancelBubble = true;
            }
            if (dragnow == e.target) {
                removeClass(e.target, “hover”);
                removeClass(e.target, “zIndex”);
                return;
            } else { //如果拽着的元素与被拽着的元素一样,不用处理
                dragnow.src = e.target.src;
                e.target.src = src;
                removeClass(e.target, “hover”);
                removeClass(e.target, “zIndex”);
            }
        }
        function dragend(e) {
            e.preventDefault();
            if (typeof e.target.style.opacity != ‘undefined’) {
                e.target.style.opacity = ‘1’;
            } else {
                e.target.style.filter = “alpha(opacity=100)”;
            } //针对FF 在dragend 时候阻止冒泡
            removeClass(e.target, “zIndex”);
        } //发生在被拖拽物体身上
        function addClass(node, newclass) {
            if (node.className.indexOf(newclass) > 0) {
                return;
            }
            node.className = node.className ? node.className + ” ” + newclass : newclass;
        }
        function removeClass(node, className) {
            if (typeof node.classList != ‘undefined’) {
                node.classList.remove(className);
            } else {
                var classarr = node.className.split(/\s+/);
                var arr = [];
                for (var i = 0; i < classarr.length; i++) {
                    if (classarr[i] == className) continue;
                    arr.push(classarr[i]);
                }
                node.className = arr.join(” “);
            }
        }
    </script>
</body>
</html>

<!DOCTYPE HTML>
<html>
<head>
<meta charset=”utf-8″/>
<title>Demo</title>
<style>
html,body{width:100%;height:100%;background-color:black;}
.wrapper{ width:500px;margin:0px auto;margin-top:80px;}
ul{list-style:none;width:500px;}
li{float:left;margin:0px 20px 20px 0px;position: relative;width:132px;height:132px;}
img{border-radius:12px;width:100px;height:100px;position: relative;-moz-user-select:none;cursor: move;}
.rubbish{position:absolute;bottom:80px;background:url(“empty.png”) no-repeat;width:128px;height:128px;left:50%;margin-left:-64px;}
.hover{border:3px dashed #fff;}
.zIndex{transform:scale(0.8,0.8);-moz-transform:scale(0.8,0.8);-webkit-transform:scale(0.8,0.8);-ms-transform:scale(0.8,0.8);-o-transform:scale(0.8,0.8);transition:transform .2s ease-in;-moz-transition:-moz-transform .2s ease-in;-o-transition:-o-transform .2s ease-in;}
</style>
</head>
<body>
<div class=”wrapper”>
<ul>
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/78/60/786031289/mzl.kcoxjsrs.png1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/88/61/886104377/mzl.dgltpgis.png1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/84/1/840146800/mzl.eiohimmz.png1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/83/59/835969177/mzl.aiikkslk.png1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/28/17/281796108/mzl.oyxfxpvw.png1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/87/85/878549709/mzl.swnecgkk.png1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/78/70/787063884/mzl.pmfectba.jpg1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/87/18/871809581/mzl.fbyoqfjw.png1.jpg”/></li&gt;
<li draggable=”true”><img src=”http://i1.mm-img.com/ios/66/93/669390657/mzl.ekoptmtx.png1.jpg”/></li&gt;

            </ul>
    </div>
    <script>
            var imgarrs = document.querySelectorAll("img");
            var dragnow=null;//目前被拽着的物体
            for(var i=0;i<imgarrs.length;i++ ){
                    addHandler(imgarrs[i],'dragstart',dragstart);
                    addHandler(imgarrs[i],'dragenter',dragenter);
                    addHandler(imgarrs[i],'dragover',dragover);
                    addHandler(imgarrs[i],'dragleave',dragleave);
                    addHandler(imgarrs[i],'drop',drop);
                    addHandler(imgarrs[i],'dragend',dragend);
            }
            function addHandler(node,type,handler){
                    if(window.addEventListener){
                            node.addEventListener(type,handler,false);
                    }else if(window.attachEvent){
                            node.attachEvent('on'+type,handler);
                    }
            }

            function dragstart(e){//被拖拽元素
            if(typeof e.target.style.opacity!='undefined'){
                    e.target.style.opacity='0.4';
            }else{
                e.target.style.filter = "alpha(opacity=40)";        
            }
                addClass(e.target,"zIndex");
                    e.dataTransfer.setData("text",e.target.src);//存储图片的src
                    dragnow=e.target;//目前被拽的物体
            }
            function dragover(e){//拖拽目标身上的效果
                    e.preventDefault();
                    e.dataTransfer.dropEffect='move';
            }
            function dragenter(e){
                    if(e.stopPropagation){e.stopPropagation();}
                    if(typeof e.target.classList !='undefined'){
                            e.target.classList.add('hover');
                    }else{
                            addClass(e.target,"hover");
                    }
            }
            function dragleave(e){
                    removeClass(e.target,"hover");
            }
            function drop(e){
                    var src = e.dataTransfer.getData("text");//获取src
                     e.preventDefault();
                     if(e.stopPropagation){
                             e.stopPropagation();
                     }else if(e.attachEvent){
                             e.cancelBubble=true;
                     }
                    if(dragnow == e.target){
                            removeClass(e.target,"hover");
                            removeClass(e.target,"zIndex");
                            return;
                    }else{//如果拽着的元素与被拽着的元素一样,不用处理
                            dragnow.src = e.target.src;
                            e.target.src = src;
                            removeClass(e.target,"hover");
                            removeClass(e.target,"zIndex");
                    }
            }
            function dragend(e){
                    e.preventDefault();
                    if(typeof e.target.style.opacity!='undefined'){
                            e.target.style.opacity='1';
                    }else{
                        e.target.style.filter = "alpha(opacity=100)";        
                    }//针对FF 在dragend 时候阻止冒泡
                    removeClass(e.target,"zIndex");
            }//发生在被拖拽物体身上

            function addClass(node,newclass){
                    if(node.className.indexOf(newclass)>0){
                            return;
                    }
                node.className = node.className?node.className+" "+newclass:newclass;
            }
            function removeClass(node,className){
                        if(typeof node.classList !='undefined'){
                                    node.classList.remove(className);
                            }else{
                                    var classarr = node.className.split(/\s+/);
                                    var arr = [];
                                    for( var i=0;i<classarr.length;i++ ){
                                            if(classarr[i] == className)continue;
                                            arr.push(classarr[i]);
                                    }
                                    node.className = arr.join(" ");
                        }
            }
    </script>

</body>
</html>
第二个例子中有一点疑惑:
我一开始想用dataTransfer.setData(“url”,src)来存储src 的,但是发现这样在IE9中getData(“url”)的时候无法获取值,所以改回”text”了。
补充:
(1)

[table=50%]
[tr][td] 属性[/td][td] 描述[/td][td] 参数[/td][/tr]
[tr][td] dropEffect[=sCursorStyle][/td][td] 设置或获取拖拽操作的类型和要显示的光标类型[/td][td] 可选的
copy 复制样式被显示
link 链接样式被显示
move 移动样式被显示
none 默认,没有鼠标样式被定义[/td][/tr]
[tr][td] effectAllowed[=sEffect][/td][td] 设置或获取数据传送操作可应用与该对象的源元素[/td][td] 可选的
copy 选项被复制
link 选项被dataTransfer作为link方式保存
move 当放置时,对象被移动至目标对象
copylink 选项是被复制还是被作为link方式保存关键在于目标对象
linkmove 选项是被作为link方式保存还是被移动关键在于目标对象
all 所有效果都被支持
none 不支持任何效果
uninitialized 默认不能通过这个属性传递任何值[/td][/tr]
[/table]

说明:

effectAllowed定义了在源对象上的操作,可定义在ondragstart事件中.

dropEffect定义了在目标对象上的操作,可定义在ondrop,ondragenter,ondragover事件中.

effectAllowed可以定义all操作,但是dropEffect可以定义copy操作.

(2)可以使用 e.dataTransfer.setDragImage(imgElement, x, y) 产生移动小图标替换原有默认的图像
var dragIcon = document.createElement(‘img’);
dragIcon.src = ‘http://www.html5rocks.com/static/images/google_logo_small.png‘;
dragIcon.width = 100;
e.dataTransfer.setDragImage(dragIcon, -10, -10);拖拽到垃圾桶上产生的图标是Google
代码片段 3

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
    <title>前端用什么开发工具</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            background-color: black;
        }
        .wrapper {
            width: 580px;
            margin: 0px auto;
            margin-top: 80px;
        }
        ul {
            list-style: none;
        }
        li {
            float: left;
            margin-right: 20px;
        }
        img {
            border-radius: 12px;
            width: 100px;
            height: 100px;
        }
        .rubbish {
            position: absolute;
            bottom: 80px;
            background: url(“data/attachment/album/201407/21/220839emsyf6bty8sfgrxf.png”) no-repeat;
            width: 128px;
            height: 128px;
            left: 50%;
            margin-left: -64px;
        }
    </style>
</head>
<body>
    <div class=”wrapper”>
        <ul>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/78/60/786031289/mzl.kcoxjsrs.png1.jpg” id=”1″ />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/88/61/886104377/mzl.dgltpgis.png1.jpg” id=”2″ />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/84/1/840146800/mzl.eiohimmz.png1.jpg” id=”3″ />
            </li>
            <li draggable=”true”>
                <img src=”http://i1.mm-img.com/ios/83/59/835969177/mzl.aiikkslk.png1.jpg” id=”4″ />
            </li>
        </ul>
    </div>
    <div class=”rubbish” id=”rubbish”></div>
    <script>
        var iconarr = document.getElementsByTagName(“li”); //icon数组
        var rubbishbin = document.getElementById(“rubbish”);
        for (var i = 0; i < iconarr.length; i++) {
            iconarr[i].ondragstart = function (ev) {
                /*拖拽开始(被拖拽元素) ondragstart 不可以写preventDefault事件*/
                ev.dataTransfer.setData(“text”, ev.target.id); //存储拖拽元素的id*/
                var dragIcon = document.createElement(‘img’);
                dragIcon.src = “http://www.html5rocks.com/static/images/google_logo_small.png”;
                dragIcon.width = 100;
                ev.dataTransfer.setDragImage(dragIcon, -10, -10);
            }
        }
        rubbishbin.ondragover = function (ev) {
            /*拖拽元素进入目标元素头
            上,不可少*/
            ev.preventDefault();
        }
        rubbishbin.ondrop = function (ev) {
            /*拖拽元素进入目标元素头上,同时鼠标松开的时候*/
            ev.preventDefault();
            if (window.addEventListener) {
                ev.stopPropagation();
            } else if (window.attachEvent) {
                ev.cancelBubble = true;
            }
            var ul = document.getElementsByTagName(“ul”)[0];
            var node = document.getElementById(ev.dataTransfer.getData(“text”)).parentNode; //拖拽的是img 移除的是Li
            ul.removeChild(node);
            rubbishbin.style.background = “url(‘data/attachment/album/201407/21/220926qem3c3dsu53u8sha.png’) no-repeat”;
        }
    </script>
</body>
</html>
<script>
</script>
web前端 开发工具|前端拖拽页面开发|开发前端页面用div
» 本文来自:前端开发者 » 《前端HTML5元素实现拖拽:drag、drop》
» 本文链接地址:https://www.rokub.com/3967.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
分享到: 更多 (0)

评论 抢沙发