获取dom中,元素style的属性值大小
// 截取
const replacePx = (str: string) => {
return Number(String(str).replace(/px/, ''))
}
const getComputedStyle = (obj: Element, param: string) => {
if (!obj) return 0
if (document?.defaultView?.getComputedStyle) {
return Number(
replacePx (document?.defaultView?.getComputedStyle(obj, null)[param])
)
} else if (window?.getComputedStyle) {
return Number(replacePx (window?.getComputedStyle(obj, null)[param]))
}
}
// 获取元素
const el = document.querySelector('.XXX')
//
const num = fnGetComputedStyle(el, 'paddingBottom')
console.log(num )
getBoundingClientRect用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性。
const H = el?.getBoundingClientRect()
console.log(H) // {bottom: 143.578125,height: 88.3125,left: 162.84375,right: 251.15625,top: 55.265625,width: 88.3125,x: 162.84375,y: 55.265625}
网友评论