繼承學(xué)習心得

萬物皆對象,函數(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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容