猿记录

一个记录、分享的博客

您的位置:主页 > 技术专栏 > javascript >

js简单拖拽

2017-04-10 17:34:26 作者:yxl 次阅读 javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生拖拽面向对象开发-versions:1.0.0</title>
</head>
<style>
*{margin: 0;}
body{position: relative;}
#drag{width: 50px;height: 50px;background-color: green;position: absolute;left:0;top:0;cursor: pointer;}
</style>
<body>
<div id="drag"></div>
<script>
window.onload = function(){
function Drag(id){
/*方便统一管理dom*/
this.doms = {
drag : document.getElementById(id),
}
}
Drag.prototype = {
constructor : Drag,
init: function(opts){
var defaults = {
opsX : 0,
opsY : 0,
width : 50,
height : 50,
bgc :  "red"
}
var opts = this.extendMany({},defaults,opts);
this.doms.drag.style.left = opts.opsX +"px";
this.doms.drag.style.top = opts.opsY + "px";
this.doms.drag.style.width = opts.width +"px";
this.doms.drag.style.height = opts.height + "px";
this.doms.drag.style.backgroundColor = opts.bgc;
this.bindEvent(opts)//如何将合并后的参数传进事件中操作,这里我不知道是否有别的更好的方法,知道的可以告知,谢谢
},
bindEvent : function(opts){
var that = this;
this.doms.drag.onmousedown = function(e){
var evn = e || window.event;
opts.opsX = evn.clientX - this.offsetLeft;
opts.opsY = evn.clientY - this.offsetTop;
document.onmousemove = function(e){
var evn = e || window.event;
var x = evn.clientX - opts.opsX;
var y = evn.clientY - opts.opsY;
var window_width  = document.documentElement.clientWidth  - that.doms.drag.offsetWidth;
            var window_height = document.documentElement.clientHeight - that.doms.drag.offsetHeight;
      /*位置判断*/
           x = ( x < 0 ) ? 0 : x;                          // 当drag到窗口最左边时
           x = ( x > window_width ) ? window_width : x;    // 当drag到窗口最右边时
           y = ( y < 0 ) ? 0 : y;                          // 当drag到窗口最上边时
           y = ( y > window_height ) ? window_height : y;  // 当drag到窗口最下边时
           
           that.doms.drag.style.left = x + "px";
           that.doms.drag.style.top  = y + "px";
}
document.onmouseup = function() {
           document.onmousemove = null;
           document.onmouseup = null;
        };
}
 
},
/*合并对象属性*/
extendMany : function() {
   var key,i = 0,len = arguments.length,target = null,copy;
   if(len === 0){
       return;
   }else if(len === 1){
       target = this;
   }else{
       i++;
       target = arguments[0];
   }
   for(var i = 0; i < len; i++){
       for(key in arguments[i]){
           copy = arguments[i][key];
           target[key] = copy;
       }
   }
   return target;
},
 
}
/*实例化*/
var drag = new Drag("drag");
drag.init({
opsX : 0,
opsY :0,
width : 50,
height:50,
bgc : "red"
})
}
</script>
</body>
</html>

凡本站注明“本站”或“投稿”的所有文章,版权均属于本站或投稿人,未经本站授权不得转载、摘编或利用其它方式使用上述作品。

编辑:yxl 关键词:
0

网友评论