window.onload=function(){
var div=document.querySelector('div');
//页面中拖拽
/*
div.onmousedown=move;
function move(e){
var ox=e.offsetX;
var oy=e.offsetY;
var ow=div.offsetWidth;
var oh=div.offsetHeight;
var cw=document.documentElement.clientWidth;
var ch=document.documentElement.clientHeight;
document.onmousemove=function(e){
var cx=e.clientX;
var cy=e.clientY;
var lefts=cx-ox;
var tops=cy-oy;
if(lefts<=0){
lefts=0
}
if(tops<=0){
tops=0;
}
if(lefts>cw-ow){
lefts=cw-ow;
}
if(tops>ch-oh){
tops=ch-oh;
}
div.style.left=lefts+'px';
div.style.top=tops+'px';
}
}
div.onmouseup=function(){
document.onmousemove=null;
}
*/
//元素拖拽(创建对象的方法封装函数)
/*
function Drag(domobj){
this.domobj=domobj;
this.cw=document.documentElement.clientWidth;
this.ch=document.documentElement.clientHeight;
this.ow=domobj.offsetWidth;
this.oh=domobj.offsetHeight;
}
Drag.prototype={
drag:function(){
var that=this;
this.domobj.onmousedown=function(e){
that.ox=e.offsetX;
that.oy=e.offsetY;
document.onmousemove=function(e){
that.cx=e.clientX;
that.cy=e.clientY;
var lefts=that.cx-that.ox;
var tops=that.cy-that.ox;
if(lefts<=0){
lefts=0;
}
if(tops<=0){
tops=0;
}
if(lefts>that.cw-that.ow){
lefts=that.cw-that.ow;
}
if(tops>that.ch-that.oh){
tops=that.ch-that.oh;
}
that.domobj.style.left=lefts+'px';
that.domobj.style.top=tops+'px';
}
}
this.domobj.onmouseup=function(){
document.onmousemove=null;
}
}
}
var obj=new Drag(div);
var div=document.querySelector('div');
obj.drag();
*/
//元素拖拽(创建对象的方法封装函数)
function Drag(domobj){
this.domobj=domobj;
this.cw=document.documentElement.clientWidth;
this.ch=document.documentElement.clientHeight;
this.ow=domobj.offsetWidth;
this.oh=domobj.offsetHeight;
}
Drag.prototype={
drag:function(){
this.down();
},
down:function(){
var that=this;
this.domobj.onmousedown=function(e){
that.ox=e.offsetX;
that.oy=e.offsetY;
that.move();
}
this.up();
},
move:function(){
var that=this;
document.onmousemove=function(e){
that.cx=e.clientX;
that.cy=e.clientY;
var lefts=that.cx-that.ox;
var tops=that.cy-that.ox;
if(lefts<=0){
lefts=0;
}
if(tops<=0){
tops=0;
}
if(lefts>that.cw-that.ow){
lefts=that.cw-that.ow;
}
if(tops>that.ch-that.oh){
tops=that.ch-that.oh;
}
that.domobj.style.left=lefts+'px';
that.domobj.style.top=tops+'px';
}
},
up:function(){
this.domobj.onmouseup=function(){
document.onmousemove=null;
}
}
}
var div=document.querySelector('div');
var obj=new Drag(div);
obj.drag();
}
元素的拖拽.js
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 1. 比如你打开一个应用,你需要点击页面下面过的相关文章中的某一篇文章,你需要先拖拽页面至相关文章,这个时候你应该...