1、H5拖拽与Js拖拽用途
JS里的拖拽三事件:onmousedown、onmousemove、onmouseup是实现交互性效果,根据鼠标的移动位置让标签元素联动。
2、H5拖拽也可以实现但更简单,例如:百度图片识别、QQ邮箱文件提交、百度网盘文件上传等,并可以获取到文件的名称、大小、修改时间。
3、实例
1)JS拖拽
let Oapp=document.querySelector("#app");
Oapp.onmousedown=function(e){
let x=e.clientX-this.offsetLeft;
let y=e.clientY-this.offsetTop;
//e.client鼠标按下点距离浏览器左上角位移,this.offsetTop距离左边的值
Oapp.onmousemove=function(e){
Oapp.style.cssText=`left:${
e.clientX-x}px;top:${
e.clientY-y}px`;
//计算盒子移动的位置,使用鼠标距离左边盒子的距离值
}
Oapp.onmouseup=function(){
Oapp.onmousemove=onmouseup=null;
//鼠标抬起的时候应该清除移动和抬起事件,不清除鼠标就无法离开盒子的范围
}
}
2)H5拖拽
//draggable是H5的新特性,为了让元素可以拖动
//使用draggable属性:值为true/false/auto
//auto是根据浏览器定义是否可以拖拽。一般图片等是默认可以拖拽的,所以draggable的默认值为true
let Oapp=document.querySelector("#app");
Oapp.ondragend=function(e){
this.style.cssText=`let:${
e.clientX}px;top:${
e.clientY}px`;
}
//补充:cssText
//cssText cssText 的本质就是设置 HTML 元素的 style 属性值
//格式:obj.style.cssText=”样式”;
//element.style.cssText =`width:300px;height:200px;border:solid 1px yellow;`
//使用累加的方法解决元素被清除的问题
//element.style.cssText +=`width:300px;height:200px;border:solid 1px yellow;`
//多加一个分号解决在IE浏览器中的问题
//Element.style.cssText += `;width:300px;height:300px;bottom:200px;right:200px;`
4、H5七事件
let Odrag=document.querySelector("#drag");
let Otarget=document.querySelector("#target");
//一、拖拽的元素事件
// 可以不用获取事件,直接书写
//1、拖拽开始时
Odrag.ondragstart=function(e){
this