HTML5新特性概述:拖放(Drag 和 drop)

2018-11-1511:47:02网页制作Comments2,711 views字数 980阅读模式

拖放是html5提供一个新的特性,这个特性增加了拖拽事件的api,和定义可以拖拽的属性。举个例子,在h5之前实现拖拽功能,其实用的是一种模拟方式,鼠标onmousedown时,获取当前的一些信息,然后在onmousemove时不断更新推拽对象的lefttop值,最后在onmouseup时对推拽对象彻底赋值,并进行释放后一系列的程序操作。现在h5出来后呢,不在需要模拟了,因为它已经有标准的事件api了,下面看例子: `文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/7869.html

<style type="text/css">
.draggable{width: 120px; height: 120px;text-align: center; line-height: 120px; background-color: #8FBC8F; color: white; border: 5px solid yellowgreen; position: absolute; top: 0;left: 0;}
</style>

<div id="draggable" class="draggable" draggable="true">
		draggable
</div>

        var dragEl = document.getElementById('draggable');
        var l = null, t = null;
		
		dragEl.ondragstart = function (e) { // 准备推拽时
			l = e.clientX - this.offsetLeft, t = e.clientY - this.offsetTop;			
		}

		dragEl.ondrag = function (e) {  // 拖拽进行时
			var x = e.clientX, y = e.clientY;				
			this.style.left = x - l + 'px';
			this.style.top = y - t + 'px';
			console.log(x, y, l , t)
		}
		
		dragEl.ondragend = function (e) {   // 拖拽结束时
			var x = e.clientX, y = e.clientY;			
			this.style.left = x - l + 'px';
			this.style.top = y - t + 'px';
		}
复制代码

`文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/7869.html

注意:拖拽对象必须把draggable属性设置为true,其他开发思维其实和以前一样的,没有多大差别,只是多了更多的监听事件而已,想要详细了解拖拽的同学可以去拖放API查看。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/7869.html

作者:IT男爵
来源:掘金文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/7869.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/zhizuo/7869.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定