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'
上面的这种利用表格关系的代码就等价于我们一开始的代码,但是这种逻辑结构更清晰
网友评论