HTML5拖拽

来源:互联网 发布:汉诺塔递归算法解析 编辑:程序博客网 时间:2024/05/22 23:19

传统的拖拽

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <style type="text/css">        .dialog{            position: absolute;            left: 100px;            top: 50px;            width: 200px;        }        .title{            background: #d7def0;            width: 100%;            height: 50px;            line-height: 50px;            text-align: center;            cursor: move;        }        .content{            background: #f0f0f0;            width: 100%;            height: 200px;        }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>   <div id="dialog" class="dialog">       <div id="title" class="title">           title       </div>       <div class="content"></div>   </div><script type="text/javascript">    var isMouseDown = false;    var lastPoint = {};    $('#title').on('mousedown',function (e) {        isMouseDown = true;        lastPoint.x = e.pageX;        lastPoint.y = e.pageY;    }).on('mousemove',function (e) {        if (isMouseDown){            var dialog = $('#dialog');            var targetX = parseInt(dialog.css('left') )+ e.pageX - lastPoint.x;            var targetY = parseInt(dialog.css('top')) + e.pageY -lastPoint.y;//限制在窗口内            if (targetX <= 0){                targetX = 0;            }            if (targetX > $(window).width() - dialog.width()){                targetX =  $(window).width() - dialog.width();            }            if (targetY < 0){                targetY = 0;            }            if (targetY > $(window).height() - dialog.height()){                targetY = $(window).height() - dialog.height();            }            dialog.css('left',targetX +'px');            dialog.css('top', targetY + 'px');            lastPoint.x = e.pageX;            lastPoint.y = e.pageY;        }    }).on('mouseup',function () {        isMouseDown = false;        lastPoint = {};    })</script></body></html>


clientx 、y



screenX 、Y




pageX. Y会随着滚动条滚动变化参照点在滚动条最左上   而client的参照点始终不变


总结:

鼠标点击事件的event对象的一些位置参数- pageX(Y):相对于整个页面的坐标,包含滚动条滚动的位置- clientX(Y):相对于浏览器可视区域的坐标- screenX(Y):相对于电脑屏幕的坐标- offsetX(Y):鼠标触发点相对于目标事件元素左上角的距离(到边框外边界,IE边框内边界)- layerX(Y):鼠标触发点相对于offsetParent元素左上角的距离(到边框外边界,IE边框内边界)



HTML5拖拽

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>    <style type="text/css">        .container{            width: 200px;            height: 200px;            background-color: yellow;        }        .containerDrop{            background-color: green;        }        .target{            width: 100px;            height: 100px;            background-color: pink;        }        .hide{            display: none;        }    </style></head><body><div id="container" class="container" ondrop="drop(event)" ondragover="dragover(event)"ondragenter="dragenter(event)"  ondragleave="dragleave(event)" ondragend="dragendContainer(event)"></div><!--drgagable属性添加到要拖动的目标上--><div id="target" class="target" draggable="true" ondragstart="dragstart(event)" ondrag="drag(event)"     ondragend="dragendTarget(event)"></div><img id="image" class="hide" src="imooc.png"><script>    var dragstart = function (e) {       e.dataTransfer.setData('Text',e.target.id);       //如果想改变拖拽中的区域的样子        e.dataTransfer.setDragImage($('#image').clone().removeClass('hide')[0],0,0);//$("#image").clone().removeClass('hide')这里是Jquery对象,而要获取dom对象则需要使用[0]来获取。        //起始坐标 0 0    };    var drop = function (e) {// 默认情况下,数据/元素不能在其他元素中被拖放。对于drop我们必须防止元素的默认处理。        e.preventDefault();        var data = e.dataTransfer.getData('Text');        e.target.appendChild(document.getElementById(data));//相当于target的div放到container中    };    var dragover = function (e) {        e.preventDefault();    };    var dragenter = function (e) {        e.preventDefault();        $('#container').addClass('containerDrop');    };    var dragleave = function (e) {        e.preventDefault();        $('#container').removeClass('containerDrop');    };    var dragendContainer = function (e) {        console.log("dragendContainer")    };    var drag = function (e) {        console.log("drag");    };    var dragendTarget = function (e) {        console.log('dragendTarget');    }</script></body></html>补充

1、Text只是个字符串,你改成别的也可以,只要跟后面的getData中的字符串保持一致就可以。2、target 事件属性可返回事件的目标节点(触发该事件的节点),语法就是:event.target,因为该事件就是id为target的div出发的,所以它获取到的就是该div。3、preventDefault()取消事件的默认动作,他的默认动作就是粉色的div无法拖进黄色的div中,所以要取消这个默认行为!

e.currentTarget指的是注册了事件监听器的对象,而e.target指的是该对象里的子对象,也是触发这个事件的对象!

ondrop 当target拖到container触发

ondragover阻止默认行为才能拖动进去

ondragenter和ondragleave 添加拖入拖出时绑定的事件

ondrag开始拖拽就触发  两个ondragend 未拖入container只打印dragendtarget


问卷生成

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>    <style type="text/css">        .page{            width: 1000px;            margin: 0 auto;        }        .left{            width: 500px;            float: left;        }        .left .container{            padding: 10px;            min-height: 500px;            box-sizing: border-box;        }        .left .containerDrop{            background-color: #EEEEEE;        }        .left .container h1{            text-align: center;        }        .right{            width: 500px;            float: left;            /*您需要并排放置两个带边框的框,可通过将 box-sizing 设置为 "border-box"。这可令浏览器呈现出带有指定宽度和高度的框,并把边框和内边距放入框中。*/            box-sizing: border-box;            border-left: 1px solid red;        }        .right .ctrlList{            padding: 10px;        }        .right .ctrlList .box{            border: 1px dashed gray;            margin-top: 10px;            margin-bottom: 10px;        }        .line{            margin-top: 10px;            margin-bottom: 10px;            padding: 5px;        }    </style></head><body><div class="page">    <div class="left">        <div id="container" class="container">            <h1>问卷</h1>        </div>    </div>    <div class="right">        <div class="ctrlList">            <div class="box" draggable="true">                <div class="line">                    <span>姓名: </span>                    <input type="text" name="name" placeholder="请输入真实姓名">                </div>            </div>            <div class="box" draggable="true">                <div class="line">                    <span>年龄: </span>                    <input type="text" name="age" placeholder="请输入年龄">                </div>            </div>            <div class="box" draggable="true">                <div class="line">                    <span>性别: </span>                    <label><input type="radio" name="gender" value="male"></label>                    <label><input type="radio" name="gender" value="female"></label>                </div>            </div>            <div class="box" draggable="true">                <div class="line">                    <span>兴趣爱好: </span>                    <label><input type="checkbox" name="hobby" value="basketball">篮球</label>                    <label><input type="checkbox" name="hobby" value="football">足球</label>                    <label><input type="checkbox" name="hobby" value="tennis">网球</label>                    <label><input type="checkbox" name="hobby" value="badminton">羽毛球</label>                    <label><input type="checkbox" name="hobby" value="tabletennis">乒乓球</label>                </div>            </div>        </div>    </div></div><script>    <!--不一定要用transfer传数据还可以这样-->    (function ($) {        var dragSrc;        $('.box').each(function (index,ele) {            $(ele).on('dragstart',function (event) {                dragSrc = this;            });        });        $('#container').on('drop',function (e) {            e.preventDefault();            $(this).append($(dragSrc).find('.line').clone());            $(this).removeClass('containerDrop');        }).on('dragover',function (e) {                e.preventDefault();        }).on('dragenter',function (e) {            e.preventDefault();            $(this).addClass('containerDrop');        }).on('dragleave',function (e) {            e.preventDefault();            $(this).removeClass('containerDrop');        })    })(jQuery);</script></body></html>

总结:1.给父元素加上margin :0 auto;子元素会居中

2.添加box-sizing 是防止加了左边框把右边挤下去 



实现的一个拼图小游戏

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>    <style type="text/css">        ul{            width: 600px;        }        li{            list-style: none;            width: 200px;            height: 200px;            float: left;        }    </style></head><body><div class="container">    <ul>        <li draggable="true"><img src="images/2.jpg"></li>        <li draggable="true"><img src="images/1.jpg"></li>        <li draggable="true"><img src="images/5.jpg"></li>        <li draggable="true"><img src="images/6.jpg"></li>        <li draggable="true"><img src="images/4.jpg"></li>        <li draggable="true"><img src="images/9.jpg"></li>        <li draggable="true"><img src="images/8.jpg"></li>        <li draggable="true"><img src="images/7.jpg"></li>        <li draggable="true"><img src="images/3.jpg"></li>    </ul></div><script>    (function ($) {        var dragSrc;        $('li').each(function (index,ele) {            $(ele).on('dragstart',function (e) {                dragSrc = this;                e.originalEvent.dataTransfer.setData('text/html',this.innerHTML)            }).on("dragover",function (e) {                e.preventDefault();            }).on('drop',function (e) {                if(dragSrc != this){//dragSrc 是指要移动的li  这里的this是原本就在那的li                    dragSrc.innerHTML = this.innerHTML;                    this.innerHTML = e.originalEvent.dataTransfer.getData('text/html');                }            })        })    })(jQuery);</script></body></html>


总结:

1.jquery中的e是进行了封装了的,dataTransfer不是绑定在e上,而是绑定在e的原始event上,所以要加上originalEvent,获取到原始的e。


文件拖拽上传

<!DOCTYPE html><html><head>  <meta charset="utf-8" />  <title>drag</title>  <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>  <style>    * {      margin: 0px;      padding: 0px;    }    .container {      width: 400px;      height: 300px;      margin: 100px auto;      border: 2px dashed black;      box-sizing: border-box;      overflow: auto;/*多出部分出现滚动条*/    }    .containerDrag {      border: 2px dashed #B0E24B;    }    .tips {      line-height: 290px;      text-align: center;    }    .file {      width: 100%;      height: 40px;      display: block;      position: relative;      list-style-type: none;    }    .text {      line-height: 40px;      font-size: 20px;      position: relative;      z-index: 2;/*不希望被进度条挡住*/      padding-left: 10px;    }    .progress {      position: absolute;      left: 0px;      top: 0px;      width: 0%;      height: 100%;      background-color: #B0E24B;    }    .loading, .right {      display: inline-block;      width: 30px;      height: 30px;      vertical-align: middle;      padding-right: 10px;    }    .loading {      background: url('images/loading.png') no-repeat;    }    .right {      background: url('images/right.png') no-repeat;    }    .wrong {      background: url('images/wrong.png') no-repeat;    }    .none {      display: none;    }  </style></head><body>  <div class="container" id="container">    <div class="tips" id="tips">拖动文件至此区域,即可上传</div>    <ul class="none" id="files">    </ul>  </div>  <div id="template" class="none">    <li class="file">      <!--显示文件名和图标-->      <span class="text"><span class="loading"></span><span class="name">aaa</span></span>      <div class="progress"></div>    </li>  </div>  <script>    (function($) {            $("#container")[0].ondragenter = function() {        if(!$("#tips").hasClass("none")) {          $("#tips").text("松开鼠标,即可上传");        }        $("#container").addClass("containerDrag");      }            $("#container")[0].ondragleave = function() {        if(!$("#tips").hasClass("none")) {          $("#tips").text("拖动文件至此区域,即可上传");        }        $("#container").removeClass("containerDrag");      }            $("#container")[0].ondragover = function(e) {        e.preventDefault();      }            $("#container")[0].ondrop = function(e) {        e.preventDefault();        if(!$("#tips").hasClass("none")) {          $("#tips").addClass("none");          $("#files").removeClass("none");        }        $("#container").removeClass("containerDrag");        var files = e.dataTransfer.files;        for (var i = 0; i < files.length; i++)/*有可能一次传了多个文件*/        {          var file = files[i];          var li = $("#template li").clone();          var icon = li.find(".loading");          var name = li.find(".name");          var progress = li.find(".progress");          name.text(file.name);          $("#files").append(li);          //simuUpload(file, progress, icon);          upload(file, progress, icon);        }      }            var simuUpload = function(file, progressEle, iconEle) {        var progress = 0;        var timer = setInterval(function() {          progress = progress + Math.floor(Math.random() * 3);          if(progress <= 100) {            progressEle.css('width', progress + '%');          } else {            clearInterval(timer);            progressEle.css('width', '0px');            iconEle.removeClass('loading').addClass('right');          }        }, 100);      }            var upload = function(file, progressEle, iconEle) {        var fd = new FormData();        fd.append("pic", file);        var xhr = new XMLHttpRequest();        xhr.open('POST', 'file:///C:/Users/admin/Desktop/新建文件夹/H5拖拽/文件上传拖拽/upload.php', true);        xhr.upload.onprogress = function (e) {          percent = 100 * e.loaded / e.total;          progressEle.css('width', percent + '%');        }        xhr.onload = function() {          if (xhr.status === 200) {            progressEle.css('width', '0px');            iconEle.removeClass('loading').addClass('right');          } else {            iconEle.removeClass('loading').addClass('wrong');          }        }        xhr.send(fd);      }        })(jQuery);  </script></body></html>


总结:

1. line-height设置块级元素 

vertical-align设置行内元素

2.注意progress和text的posiiton设置


两款拖拽插件

dragdealer

jquery.pep.js

原创粉丝点击