控制元素移动

class SuperMarry {
    constructor({el, step}) {
        this.target = el
        this.step = step
        this.currentKey = null
        this.keys = [
            { name: 'top', key: 38 },
            { name: 'right', key: 39 },
            { name: 'bottom', key: 40 },
            { name: 'left', key: 37 },
        ]
        this.init()
    }

    getTargetPosition () {
        return this.target.getBoundingClientRect()
    }

    top () {
        let { left, top } = this.getTargetPosition()
        if (top > 0) {
            this.target.style.top = top - this.step
        }
        return this
    }
    left () {
        let { left } = this.getTargetPosition()
        if (left > 0) {
            this.target.style.left = left - this.step
        }
        return this
    }
    right () {
        let { left, width } = this.getTargetPosition()
        if (left > window.innerWidth - width) {
            return false
        }
        this.target.style.left = left + this.step
        return this

    }
    bottom () {
        let { top, height } = this.getTargetPosition()
        if (top < window.innerHeight - height) {
            this.target.style.top = top + this.step
        }
        return this
    }
    init () {
        const _this = this
        setInterval(() => {
            if (_this.currentKey) {
                const { name } = _this.keys.find(item => item.key === this.currentKey)
                _this[name]()
            }
        }, _this.speed)
        document.addEventListener('keydown', function (e) {
            const keys = _this.keys.map(o => o.key)
            if (keys.indexOf(e.keyCode) !== -1) {
                _this.currentKey = e.keyCode
            }
        })
        document.addEventListener('keyup', function (e) {
            _this.currentKey = null
        })
    }
}

window.onload = function () {
    new SuperMarry({
        el: document.getElementById('box'), 
        step: 5,
        speed: 10
    })
}

```css
body {
        padding: 0;
        margin: 0;
    }
    #box {
        position: absolute;
        left: 200px;
        top: 500px;
        width: 100px;
        height: 100px;
        border: 1px solid #000;
        background: red;
    }
<div id='box'></div>