表驱动编程

if(this.position === 'top'){
    content.style.left = left + window.scrollX + 'px'
    content.style.top = top + window.scrollY + 'px'
}else if(this.position === 'bottom'){
    content.style.left = left + window.scrollX + 'px'
    content.style.top = top  + height + window.scrollY + 'px'
}else if(this.position === 'left'){
    let {height: height2} = content.getBoundingClientRect();
    content.style.left = left  + window.scrollX + 'px'
    content.style.top = top  + (height-height2)/2 + window.scrollY + 'px'
}else if(this.position === 'right'){
    let {height: height2} = content.getBoundingClientRect();
    content.style.left = left + width+ window.scrollX + 'px'
    content.style.top = top  + (height-height2)/2 + window.scrollY + 'px'
}

上面的代码结构大体相同,这时候我们就可以画个表格,一一对应了

我们可以通过一个对象构造这种表格的关系

let positions = {
    top: {
        left: left + window.scrollX,
        top: top + window.scrollY
    },
    bottom: {
        left: left + window.scrollX,
        top: top  + height + window.scrollY
    },
    left: {
        left: left  + window.scrollX,
        top: top  + (height-height2)/2 + window.scrollY
    },
    right: {
        left: left + width+ window.scrollX,
        top: top  + (height-height2)/2 + window.scrollY
    }
}
content.style.left = positions[this.position].left + 'px'
content.style.top = positions[this.position].top + 'px'

上面的这种利用表格关系的代码就等价于我们一开始的代码,但是这种逻辑结构更清晰

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容