最近造轮子,在写 popover 组件时写出了一段很臃肿的代码,有许多 if,else,如下
positionContent () {
const {contentWrapper, triggerWrapper} = this.$refs
document.body.appendChild(contentWrapper)
let {width, height, top, left} = triggerWrapper.getBoundingClientRect()
let {height: height2} = contentWrapper.getBoundingClientRect()
if (this.position === 'top') {
contentWrapper.style.left = left + window.scrollX + 'px'
contentWrapper.style.top = top + window.scrollY + 'px'
} else if (this.position === 'bottom') {
contentWrapper.style.left = left + window.scrollX + 'px'
contentWrapper.style.top = top + height + window.scrollY + 'px'
} else if (this.position === 'left') {
contentWrapper.style.left = left + window.scrollX + 'px'
contentWrapper.style.top = top + window.scrollY +
(height - height2) / 2 + 'px'
} else if (this.position === 'right') {
contentWrapper.style.left = left + window.scrollX + width + 'px'
contentWrapper.style.top = top + window.scrollY +
(height - height2) / 2 + 'px'
}
}
以上是不是有很多重复的元素,可以用一张表来表示
top | bottom | left | right | |
---|---|---|---|---|
top | value | value | value | value |
left | value | value | value | value |
参考《代码大全》第十八章可使用表驱动编程来优化。
positionContent () {
const {contentWrapper, triggerWrapper} = this.$refs
document.body.appendChild(contentWrapper)
let {width, height, top, left} = triggerWrapper.getBoundingClientRect()
let {height: height2} = contentWrapper.getBoundingClientRect()
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 + window.scrollY + (height - height2) / 2
},
right: {
left: left + window.scrollX + width ,
top: top + window.scrollY + (height - height2) / 2
}
}
contentWrapper.style.left = positions[this.position].left + 'px'
contentWrapper.style.top = positions[this.position].top + 'px'
}
这是本人的造轮子项目,欢迎来提 issue 和 star https://github.com/zyqq/wheel
网友评论