批量获取dom指定样式属性值
interface Option {
[key: string]: string
}
const getStyleAttribute = (el: any, option: Option): any => {
const newOption = {}
try {
const attributeList = Object.keys(option)
const styleList = getComputedStyle(el, null) || {}
attributeList.forEach((item) => {
newOption[item] =
option[item] === 'number'
? Number(styleList[item]?.replace(/[^\d.]*/g, '') || 0)
: styleList[item]
})
} catch (error) {
console.log('getStyleAttribute', error)
}
return newOption
}
const defaultBox = document.querySelector('#default-box')
const { marginTop: tabsTop } = getStyleAttribute(defaultBox, {
marginTop: 'number',
})