继承学习心得

2017-10-13  本文已影响0人  嫚荹囩鍴

万物皆对象,函数也是对象的一种,函数有原型对象,我们可以通过原型对象来继承其他对象的属性跟方法,比如,我们构造一个具有拖拽功能的函数对象:

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();
        }
    }
}

这个函数中有元素,这个元素自带属性,我们还给这个元素绑定了一个onmousedown的方法或者行为,这个行为又调用了一些功能方法,具体方法为:

// 方法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;
}

以上这个拖拽功能函数只是具有普通的拖拽功能,现在我们在HTML中布局三个盒子,其样式跟结构的代码如下:

<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>
上一篇 下一篇

猜你喜欢

热点阅读