61原生JS:拖拽

```html:run
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
*{
margin:0;
padding:0;
}
div{
position: absolute;
left:0;
top:0;
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="div"></div>
<script>
var oDiv=document.getElementById('div');
oDiv.onmousedown=down;
function processThis(fn,obj){
return function(e){
fn.call(obj,e)
}
}
function down(e){
e=e||window.event;
this.x=this.offsetLeft;
this.y=this.offsetTop;
this.mx= e.clientX;
this.my= e.clientY;
if(this.setCapture){
this.setCapture();
this.onmousemove=processThis(move,this);
this.onmouseup=processThis(up,this);
}else{
document.onmousemove=processThis(move,this);
document.onmouseup=processThis(up,this);
}

}
function move(e){
e=e||window.event;
this.style.left=this.x+(e.clientX-this.mx)+'px';
//this.x:移动前offsetLeft值;(e.clientX-this.mx):鼠标横向移动的距离,即盒子横向移动的距离
this.style.top=this.y+(e.clientY-this.my)+'px';
//this.y:移动前offsetTop值;(e.clientX-this.mx):鼠标纵向移动的距离,即盒子纵向移动的距离
}
function up(){
if(this.releaseCapture){
this.releaseCapture();
this.onmousemove=null;
this.onmouseup=null;
}else{
document.onmousemove=null;
document.onmouseup=null;
}

}
</script>
</body>
</html>
```

附一、jquery和zepto的区别:
1,针对移动端程序,Zepto有一些基本的触摸事件可以用来做触摸屏交互(tap事件、swipe事件),Zepto是不支持IE浏览器的。
2,Dom操作的区别:添加id时jQuery不会生效而Zepto会生效。
3,事件触发的区别:使用 jQuery 时 load 事件的处理函数不会执行;使用 Zepto 时 load 事件的处理函数会执行。
4,事件委托的区别:
5,width()和height()的区别:Zepto由盒模型(box-sizing)决定,用.width()返回赋值的width,用.css('width')返回加border等的结果;jQuery会忽略盒模型,始终返回内容区域的宽/高(不包含padding、border)。
6,offset()的区别:Zepto返回{top,left,width,height};jQuery返回{width,height}。
7,Zepto无法获取隐藏元素宽高,jQuery 可以。
8,Zepto中没有为原型定义extend方法而jQuery有。
9,Zepto 的each 方法只能遍历 数组,不能遍历JSON对象。
10,Zepto在操作dom的selected和checked属性时尽量使用prop方法,在读取属性值的情况下优先于attr。Zepto获取select元素的选中option不能用类似jQuery的方法$('option[selected]'),因为selected属性不是css的标准属性。应该使用$('option').not(function(){ return !this.selected })。

猜你喜欢

转载自www.cnblogs.com/gushixianqiancheng/p/10966989.html