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. 比如你打开一个应用,你需要点击页面下面过的相关文章中的某一篇文章,你需要先拖拽页面至相关文章,这个时候你应该...