美文网首页
获取dom中,元素style的属性值大小

获取dom中,元素style的属性值大小

作者: 码农私房菜 | 来源:发表于2021-04-25 20:50 被阅读0次

获取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}

相关文章

网友评论

      本文标题:获取dom中,元素style的属性值大小

      本文链接:https://www.haomeiwen.com/subject/pfzerltx.html