萬物皆對象,函數(shù)也是對象的一種,函數(shù)有原型對象,我們可以通過原型對象來繼承其他對象的屬性跟方法,比如,我們構(gòu)造一個具有拖拽功能的函數(shù)對象:
function DragBox(boxId) {
if (boxId == undefined) {
return;
}
this.ele = document.getElementById(boxId);
var self = this;
this.ele.onmousedown = function(e) {
e.preventDefault();
self.detaX = e.clientX - self.ele.offsetLeft;
self.detaY = e.clientY - self.ele.offsetTop;
self.start();
document.onmouseup = function() {
self.stop();
}
}
}
這個函數(shù)中有元素,這個元素自帶屬性,我們還給這個元素綁定了一個onmousedown的方法或者行為,這個行為又調(diào)用了一些功能方法,具體方法為:
// 方法1: 開始
DragBox.prototype.start = function() {
var self = this;
document.onmousemove = function(e) {
var x = e.clientX - self.detaX;
var y = e.clientY - self.detaY;
self.move(x, y);
}
}
// 方法2: 移動
DragBox.prototype.move = function(x, y) {
var self = this;
self.ele.style.left = x + "px";
self.ele.style.top = y + "px";
}
// 方法3: 停止
DragBox.prototype.stop = function() {
document.onmousemove = null;
}
以上這個拖拽功能函數(shù)只是具有普通的拖拽功能,現(xiàn)在我們在HTML中布局三個盒子,其樣式跟結(jié)構(gòu)的代碼如下:
<style>
*{margin:0;padding:0}
body{
overflow:hidden;
}
div {
width: 100px;
height: 100px;
background: -webkit-radial-gradient(rgba(255,255,0,1) 2%, rgba(0,255,255,1) 98%);
border-radius:50%;
position: absolute;
}
#box2 {
background: -webkit-radial-gradient(rgba(0,255,255,1) 2%,rgba(255,0,255,1) 98%);
top:150px;
}
#box3 {
background: -webkit-radial-gradient(rgba(255,255,255,1) 2%, rgba(255,0,255,1) 98%);
top:300px;
}
</style>
<body>
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
</body>