您的位置:首页 > 其它

组件开发

2015-12-21 22:56 190 查看
//参数不写会报错和参数顺序的问题(json和配置/默认参数)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#div1,#div2,#div3,#div4{
width: 100px;
height: 100px;
position: absolute;
top: 0;
cursor: pointer;
}
#div1{
left: 0;
background-color: red;
}
#div2{
left: 100px;
background-color: yellow;
}
#div3{
left: 200px;
background-color: green;
}
#div4{
left: 300px;
background-color: blue;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<script>
window.onload = function(){
var d1 = new Drag();
d1.init({ //配置参数
"id":"div1"
});

var d2 = new Drag();
d2.init({
"id":"div2",
"fnDown":function(){
document.title = "111";
}
});

var d3 = new Drag();
d3.init({
"id":"div3",
"fnDown":function(){
document.title = "222";
},
"fnUp":function(){
document.title = "333";
}
});

var d4 = new Drag();
d4.init({
"id":"div4",
"fnUp":function(){
document.title = "888";
}
});
};

function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}

function Drag(){
this.oDiv = null;
this.disX = 0;
this.disY = 0;
this.settings = { //默认参数
"fnDown":function(){}, //shit dowm/down
"fnUp":function(){}
};
}
Drag.prototype.init = function(opt){
var This = this;
this.oDiv = document.getElementById(opt.id);
extend(this.settings,opt); //配置覆盖默认
console.log(this.settings);
this.oDiv.onmousedown = function(ev){
var oEvent = ev||event;
This.fnDown(oEvent);
return false;
};
};
Drag.prototype.fnDown = function(ev){
this.settings.fnDown(); //调用默认
this.disX = ev.clientX - this.oDiv.offsetLeft;
this.disY = ev.clientY - this.oDiv.offsetTop;
var This = this;
document.onmousemove = function(ev){
var oEvent = ev||event;
This.fnMove(oEvent);
};
document.onmouseup = function(){
This.fnUp();
};
};
Drag.prototype.fnMove = function(ev){
var x = ev.clientX - this.disX;
var y = ev.clientY - this.disY;
this.oDiv.style.left = x + "px";
this.oDiv.style.top = y + "px";
};
Drag.prototype.fnUp = function(){
this.settings.fnUp();
document.onmousemove = document.onmouseup = null;
};

</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: