拖拽

栏目: CSS · 发布时间: 6年前

内容简介:拖拽
  • DataTransfer 对象:退拽对象用来传递的媒介,使用一般为Event.dataTransfer。
  • draggable 属性:就是标签元素要设置draggable=true,否则不会有效果,例如:

    列表1

  • ondragstart 事件:当拖拽元素开始被拖拽的时候触发的事件,此事件作用在被拖曳元素上

  • ondragenter 事件:当拖曳元素进入目标元素的时候触发的事件,此事件作用在目标元素上
  • ondragover 事件:拖拽元素在目标元素上移动的时候触发的事件,此事件作用在目标元素上
  • ondrop 事件:被拖拽的元素在目标元素上同时鼠标放开触发的事件,此事件作用在目标元素上
  • ondragend 事件:当拖拽完成后触发的事件,此事件作用在被拖曳元素上
  • Event.preventDefault() 方法:阻止默认的些事件方法等执行。在ondragover中一定要执行preventDefault(),否则ondrop事件不会被触发。另外,如果是从其他应用软件或是文件中拖东西进来,尤其是图片的时候,默认的动作是显示这个图片或是相关信息,并不是真的执行drop。此时需要用用document的ondragover事件把它直接干掉。
  • Event.effectAllowed 属性:就是拖拽的效果。
    <divclass="dustbin"><br/>垃<br/>圾<br/>箱</div>
    <divclass="dragbox">
        <divclass="draglist"title="拖拽我"draggable="true">列表1</div>
        <divclass="draglist"title="拖拽我"draggable="true">列表2</div>
        <divclass="draglist"title="拖拽我"draggable="true">列表3</div>
        <divclass="draglist"title="拖拽我"draggable="true">列表4</div>
        <divclass="draglist"title="拖拽我"draggable="true">列表5</div>
        <divclass="draglist"title="拖拽我"draggable="true">列表6</div>
    </div>
    <divclass="dragremind"></div>
    

JS代码如下:

var $ = function(selector){
    /*简单的选择器方法*/
    ...
};

var eleDustbin = $(".dustbin")[0], eleDrags = $(".draglist"), lDrags = eleDrags.length, eleRemind = $(".dragremind")[0], eleDrag = null;
for (var i=0; i<lDrags; i+=1) {
    eleDrags[i].onselectstart = function(){
        return false;
    };
    eleDrags[i].ondragstart = function(ev){
        /*拖拽开始*/
        //拖拽效果
        ev.dataTransfer.effectAllowed = "move";
        ev.dataTransfer.setData("text", ev.target.innerHTML);
        ev.dataTransfer.setDragImage(ev.target, 0, 0);
        eleDrag = ev.target;
        return true;
    };
    eleDrags[i].ondragend = function(ev){
        /*拖拽结束*/
        ev.dataTransfer.clearData("text");
        eleDrag = null;
        return false
    };
}
eleDustbin.ondragover = function(ev){
    /*拖拽元素在目标元素头上移动的时候*/
    ev.preventDefault();
    return true;
};

eleDustbin.ondragenter = function(ev){
    /*拖拽元素进入目标元素头上的时候*/
    this.style.color = "#ffffff";
    return true;
};
eleDustbin.ondrop = function(ev){
    /*拖拽元素进入目标元素头上,同时鼠标松开的时候*/
    if (eleDrag) {
        eleRemind.innerHTML = '<strong>"' + eleDrag.innerHTML + '"</strong>被扔进了垃圾箱';
        eleDrag.parentNode.removeChild(eleDrag);
    }
    this.style.color = "#000000";
    return false;
};

完整例子2

<!DOCTYPE html>
<html>
<head>
    <metacharset="UTF-8">
    <title></title>
</head>
<body>
<divid="demo1">
    <ulclass="panel-list">
        <liclass="panel-item"></li>
        <liclass="panel-item"></li>
        <liclass="panel-item"></li>
        <liclass="panel-item"></li>
        <liclass="panel-item"></li>
    </ul>
    <h2>拖拽下面的方块到上面任意容器中</h2>

    <!-- 设置draggable使元素成为可拖拽元素 -->
    <spanclass="movable"id="demo1-src"draggable="true"></span>

    <style>
        #demo1 {
            margin: 20px;
        }
        #demo1 .panel-list {
            overflow: hidden;
            list-style: none;
            margin: 0;
            padding: 0;
        }
        #demo1 .panel-item {
            float: left;
            margin-right: 30px;
            width: 100px;
            height: 100px;
            background: #ddd;
            border: 1px solid #ddd;
        }
        #demo1-src {
            display: inline-block;
            width: 50px;
            height: 50px;
            background: purple;
        }
        #demo1 .over {
            border: 1px dashed #000;
            -webkit-transform: scale(0.8, 0.8);
        }
    </style>
    <script>
        (function(){

            var dnd = {
                // 初始化
                init: function(){
                    var me = this;
                    me.src = document.querySelector('#demo1-src');
                    me.panelList = document.querySelector('.panel-list');

                    // 为拖拽源监听dragstart,设置关联数据
                    me.src.addEventListener('dragstart', me.onDragStart, false);

                    // 拖拽鼠标移入元素,在拖放目标上设置视觉反馈
                    me.panelList.addEventListener('dragenter', me.onDragEnter, false);

                    // 取消元素dragover默认行为,使其可拖放
                    me.panelList.addEventListener('dragover', me.onDragOver, false);

                    // 拖拽移出元素,清除视觉反馈
                    me.panelList.addEventListener('dragleave', me.onDragLeave, false);

                    // 鼠标释放,在拖放目标上接收数据并处理
                    me.panelList.addEventListener('drop', me.onDrop, false);
                },
                onDragStart: function(e){
                    console.log(e)
                    e.dataTransfer.setData('text/plain', 'demo1-src');
                },
                onDragEnter: function(e){
                    if (e.target.classList.contains('panel-item')) {
                        e.target.classList.add('over');
                    }
                },
                onDragLeave: function(e){
                    if (e.target.classList.contains('panel-item')) {
                        e.target.classList.remove('over');
                    }
                },
                onDragOver: function(e){
                    e.preventDefault();
                },
                onDrop: function(e){
                    var id = e.dataTransfer.getData('text/plain');
                    var src = document.getElementById(id);
                    var target = e.target;
                    if (target.classList.contains('panel-item')) {
                        target.appendChild(src);
                        target.classList.remove('over');
                    }
                }

            };

            dnd.init();
        }());
    </script>
</div>
</body>
</html>

用JavaScript事件方法

原理

①鼠标按下+鼠标移动 → 拖拽
②鼠标松开 → 无拖拽
③鼠标偏移 → 拖拽距离

① onmousedown + onmousemove → startDrag()
② onmouseup → stopDrag()
③ ……

关键点就是让鼠标的偏移值赋给拖拽对象。

js实例

var params = {
	left: 0,
	top: 0,
	currentX: 0,
	currentY: 0,
	flag: false
};
//获取相关CSS属性
var getCss = function(o,key){
	return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key]; 	
};

//拖拽的实现
var startDrag = function(bar, target, callback){
	if(getCss(target, "left") !== "auto"){
		params.left = getCss(target, "left");
	}
	if(getCss(target, "top") !== "auto"){
		params.top = getCss(target, "top");
	}
	//o是移动对象
	bar.onmousedown = function(event){
		params.flag = true;
		if(!event){
			event = window.event;
			//防止IE文字选中
			bar.onselectstart = function(){
				return false;
			}  
		}
		var e = event;
		params.currentX = e.clientX;
		params.currentY = e.clientY;
	};
	document.onmouseup = function(){
		params.flag = false;	
		if(getCss(target, "left") !== "auto"){
			params.left = getCss(target, "left");
		}
		if(getCss(target, "top") !== "auto"){
			params.top = getCss(target, "top");
		}
	};
	document.onmousemove = function(event){
		var e = event ? event: window.event;
		if(params.flag){
			var nowX = e.clientX, nowY = e.clientY;
			var disX = nowX - params.currentX, disY = nowY - params.currentY;
			target.style.left = parseInt(params.left) + disX + "px";
			target.style.top = parseInt(params.top) + disY + "px";
		}
		
		if (typeof callback == "function") {
			callback(parseInt(params.left) + disX, parseInt(params.top) + disY);
		}
	}	
};

HTML/CSS

<styletype="text/css">
#box{position:absolute; left:100px; top:100px; padding:5px; background:#f0f3f9; font-size:12px; -moz-box-shadow:2px 2px 4px #666666; -webkit-box-shadow:2px 2px 4px #666666;}
#main{border:1px solid #a0b3d6; background:white;}
#bar{line-height:24px; background:#beceeb; border-bottom:1px solid #a0b3d6; padding-left:5px; cursor:move;}
#content{width:420px; height:250px; padding:10px 5px;}
</style>

<divid="box">
    <divid="main">
        <divid="bar">拖拽</div>
        <divid="content">
            内容……
        </div>
    </div>
</div>
<scripttype="text/javascript">
    var oBox = document.getElementById("box");//被拖拽的对象
    var oBar = document.getElementById("bar");//触发拖拽的对象
    startDrag(oBar, oBox);
</script>

拖拽实例

<!doctype html>
<htmllang="en">
<head>
    <metacharset="UTF-8">
    <metaname="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <metahttp-equiv="X-UA-Compatible"content="ie=edge">
    <title>drag</title>
    <style>
        .div1{width: 1000px;height: 100px;background: #eeeeee;position: relative;margin: 0 auto;}
        .div2{width: 100px;height: 100px;background: #dddddd;position: absolute;top: 0px;left: 0px;cursor: pointer;}
    </style>
</head>
<body>
<divclass="div1">
    <divclass="div2"></div>
</div>

<script>
    var params = {
        left: 0,
        top: 0,
        currentX: 0, //点击的时候记录鼠标坐标
        currentY: 0,
        flag: false
    };
    var parentPara = { //移动的范围
        height:0,
        width:0
    };
    var son = {
        width:0,
        height:0,
    }

    //获取相关CSS属性
    var getCss = function(o,key){
        return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];
    };

    //拖拽的实现
    var startDrag = function(bar, target, parentBox,callback){
        if(getCss(target, "left") !== "auto"){
            params.left = getCss(target, "left");
        }
        if(getCss(target, "top") !== "auto"){
            params.top = getCss(target, "top");
        }
        //父盒子宽高
        if(parentBox){
            parentPara.width = parentBox.scrollWidth - target.scrollWidth;
            parentPara.height = parentBox.scrollHeight - target.scrollHeight;
            console.log(parentPara);
        }

        //子盒子宽高

        //o是移动对象
        bar.onmousedown = function(event){
            params.flag = true;
            if(!event){
                event = window.event;
                //防止IE文字选中
                bar.onselectstart = function(){
                    return false;
                }
            }
            var e = event;
            params.currentX = e.clientX;
            params.currentY = e.clientY;
        };
        document.onmouseup = function(){
            params.flag = false;
            if(getCss(target, "left") !== "auto"){
                params.left = getCss(target, "left");
            }
            if(getCss(target, "top") !== "auto"){
                params.top = getCss(target, "top");
            }
        };
        document.onmousemove = function(event){
            var e = event ? event: window.event;
            if(params.flag){

                var nowX = e.clientX, nowY = e.clientY; //鼠标位置
                var disX = nowX - params.currentX, disY = nowY - params.currentY; //移动的距离
                var succX = parseInt(params.left) + disX, succY = parseInt(params.top) + disY;
                if(succX<=0){succX =0 }
                if(succY<=0){succY =0 }
                if(succX>=parentPara.width){succX =parentPara.width }
                if(succY>=parentPara.height){succY =parentPara.height }
                target.style.left = succX + "px";
                target.style.top = succY + "px";
            }

            if (typeof callback == "function") {
                callback(parseInt(params.left) + disX, parseInt(params.top) + disY);
            }
        }
    };

    var oBox = document.querySelector(".div2");//被拖拽的对象
    var oBar = document.querySelector(".div2");//触发拖拽的对象
    var oMain = document.querySelector(".div1");//父盒子
    startDrag(oBar, oBox, oMain);
</script>
</body>
</html>

结合滚轮待修改

<!doctype html>
<htmllang="en">
<head>
    <metacharset="UTF-8">
    <metaname="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <metahttp-equiv="X-UA-Compatible"content="ie=edge">
    <title>drag</title>
    <style>
        .div1{width: 1000px;height: 100px;background: #eeeeee;position: relative;margin: 0 auto;}
        .div2{width: 100px;height: 100px;background: #dddddd;position: absolute;top: 0px;left: 0px;cursor: pointer;}
    </style>
</head>
<body>
<divclass="div1">
    <divclass="div2"></div>
</div>

<script>
    var a = 0;
    var params = {
        left: 0,
        top: 0,
        currentX: 0, //点击的时候记录鼠标坐标
        currentY: 0,
        flag: false
    };
    var parentPara = { //移动的范围
        height:0,
        width:0
    };
    var son = {
        width:0,
        height:0,
    }

    //获取相关CSS属性
    var getCss = function(o,key){
        return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];
    };

    //拖拽的实现
    var startDrag = function(bar, target, parentBox,callback){
        if(getCss(target, "left") !== "auto"){
            params.left = getCss(target, "left");
        }
        if(getCss(target, "top") !== "auto"){
            params.top = getCss(target, "top");
        }
        //可移动宽高
        if(parentBox){
            parentPara.width = parentBox.scrollWidth - target.scrollWidth;
            parentPara.height = parentBox.scrollHeight - target.scrollHeight;
        }

        //子盒子宽高

        //o是移动对象
        bar.onmousedown = function(event){
            params.flag = true;
            if(!event){
                event = window.event;
                //防止IE文字选中
                bar.onselectstart = function(){
                    return false;
                }
            }
            var e = event;
            params.currentX = e.clientX;
            params.currentY = e.clientY;
        };
        document.onmouseup = function(){
            params.flag = false;
            if(getCss(target, "left") !== "auto"){
                params.left = getCss(target, "left");
            }
            if(getCss(target, "top") !== "auto"){
                params.top = getCss(target, "top");
            }
        };
        document.onmousemove = function(event){
            var e = event ? event: window.event;
            if(params.flag){

                var nowX = e.clientX, nowY = e.clientY; //鼠标位置
                var disX = nowX - params.currentX, disY = nowY - params.currentY; //移动的距离
                var succX = parseInt(params.left) + disX, succY = parseInt(params.top) + disY;
                succX = succX<=0 ? succX = 0 :succX;
                succY = succY<=0 ? succY = 0 :succY;
                succX = succX>=parentPara.width ? succX =parentPara.width : succX;
                succY = succY>=parentPara.height ? succY = parentPara.height : succY;
                a = parseInt(succX/50)
                target.style.left = succX + "px";
                target.style.top = succY + "px";
            }

            if (typeof callback == "function") {
                callback(parseInt(params.left) + disX, parseInt(params.top) + disY);
            }
        }
    };

    var oBox = document.querySelector(".div2");//被拖拽的对象
    var oBar = document.querySelector(".div2");//触发拖拽的对象
    var oMain = document.querySelector(".div1");//父盒子
    startDrag(oBar, oBox, oMain);
</script>
<script>
    window.onload = function(){
        var odiv1 = document.querySelector('.div1');
        var explorer = navigator.userAgent;

        if (explorer.indexOf("Firefox") >= 0 ) {
            odiv1.addEventListener('DOMMouseScroll',wheel)//火狐
        } else if(explorer.indexOf('Trident')>-1&&explorer.indexOf('rv:11')>-1){
            odiv1.addEventListener('mousewheel',wheel)//ie
        }else {
            odiv1.addEventListener('wheel',wheel)//谷歌
        }


        function wheel(ev){
            var e = ev || window.event;

            if (explorer.indexOf("Firefox") >= 0) {
                a+=e.detail/3; //火狐
            } else{
                a+=e.wheelDelta/120; //谷歌
            }
            a = a<=0 ? a =0 : a
            a = a>=parentPara.width/50 ? a =parentPara.width/50 : a
            params.left = a*50;
            oBox.style.left = a*50 + "px";
        }
    }
</script>
</body>
</html>

jQuery拖拽

<!DOCTYPE html>
<htmllang="en">
<head>
    <metacharset="UTF-8">
    <title>判断拖拽速度</title>
</head>
<body>

<styletype="text/css">
    #drag{width:400px;height:300px; background: #999;cursor:move;position:absolute;top:300px;left:300px;border:solid 1px #ccc;}
</style>

<scriptsrc="js/jquery-2.0.3.min.js"></script>
<script>
    $(function(){

        var dragging = false;
        var iX, iY;
        var main = {X:0,Y:0};
        var newmain = {X:0,Y:0,X2:0,Y2:0}; //2为去正后的数
        var data1,data2;

        $("#drag").mousedown(function(e){
            data1 = new Date().getTime();//起始时间
            dragging = true;
            main.X = $(this).offset().left;
            main.Y = $(this).offset().top;
            iX = e.clientX - main.X;
            iY = e.clientY - main.Y;
            this.setCapture && this.setCapture();
            return false;
        });
        document.onmousemove = function(e){
            if (dragging) {
                var e = e || window.event;
                var oX = e.clientX - iX;
                var oY = e.clientY - iY;
                $("#drag").css({"left":oX + "px", "top":oY + "px"});
                return false;
            }
        };
        $(document).mouseup(function(e){
            dragging = false;
            data2 = new Date().getTime();  //释放的时间

            //拖动的速度
            newmain.X = ($("#drag").offset().left - main.X)/(data2-data1);
            newmain.Y = ($("#drag").offset().top - main.Y)/(data2-data1);

            //速度取正
            newmain.X2 = newmain.X < 0 ? -newmain.X : newmain.X;
            newmain.Y2 = newmain.Y < 0 ? -newmain.Y : newmain.Y;

            //判断那个方向
            var direction = newmain.X2 > newmain.Y2 ? "X" : "Y";

            if (direction == "X") {
                direction =  newmain.X < 0 ? "X2" : "X"   //左右判断
            }

            if (direction == "Y") {
                direction =  newmain.Y < 0 ? "Y2" : "Y"  //上下判断
            }

            console.log(direction + "----------X2:左边;X:右边;Y2:上边;Y:下边")

            // 如果左右快速拖动
            if (newmain.X2 > 1) {

                console.log("快速的朝"+ direction +"方向拖动!!!")

                var num = direction == "X" ? 300 : -300
                $("#drag").animate({left:main.Y + num},500)

            }else if (newmain.Y2 > 1) {  //如果快速上下移动

                console.log("快速的朝"+ direction +"方向拖动!!!")

                var num = direction == "Y" ? 300 : -300
                $("#drag").animate({top:main.X + num},500)

            }else {
                $("#drag").animate({top:main.X,left:main.Y},500) //速度太慢,返回原点回去
                console.log('回去')
            }
        })
    })
</script>


<divid="drag">
</div>

</body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Coming of Age in Second Life

Coming of Age in Second Life

Tom Boellstorff / Princeton University Press / 2008-04-21 / USD 29.95

The gap between the virtual and the physical, and its effect on the ideas of personhood and relationships, is the most interesting aspect of Boellstorff's analysis... Boellstorff's portrayal of a virt......一起来看看 《Coming of Age in Second Life》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具