继承应用

2017-10-12  本文已影响0人  邱帅123

继承函数 DragBox

<style>
        div {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }

        #box2 {
            background: green;
        }

        #box3 {
            background: blue;
        }
        *{margin:0;padding:0}
        body{height: 100vh}
    </style>
  
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>

    <script src="DragBox.js"></script>
    <script>
/*
            DragBoxText  继承 DragBox
            需要在继承的基础上,实现在移动时,显示自己的坐标

            步骤:
                1. 继承属性
                2. 继承方法
                3. 修改 move 方法

            【练习】 你实现继承的 DragBoxText
        */
        function DragBoxText(boxId){
            DragBox.call(this,boxId)
        }
        DragBoxText.prototype = new DragBox()
        DragBoxText.prototype.move = function(x,y){
            DragBox.prototype.move.call(this,x,y)
            this.ele.innerHTML = x +","+ y
        }
        
        DragBox2.prototype = new DragBox()
        function DragBox2(boxId){
            DragBox.call(this,boxId)
        }
        DragBox2.prototype.move = function(x,y){
            
            if (x<0)
            {
                x=0
            }else if (x>document.body.clientWidth-this.ele.offsetWidth)
            {
                x = document.body.clientWidth-this.ele.offsetWidth
            }
            if (y<0)
            {
                y=0
            }else if (y>document.body.clientHeight-this.ele.offsetHeight)
            {
                y = document.body.clientHeight-this.ele.offsetHeight
            }
            DragBox.prototype.move.call(this,x,y)
            
        }
        
        // 让 box1 具备拖拽的能力
        new DragBox("box1");
        new DragBoxText("box2");
        new DragBox2("box3");
    </script>

遇到的问题

1.获取屏幕高度
应该先给body设置高度
如: body{ height: 100vh} (vh表示百分比)

上一篇 下一篇

猜你喜欢

热点阅读