ryu-f
9/6/2019 - 9:01 AM

vanilaで複数スタイル

const reUnit = /width|height|top|left|right|bottom|margin|padding/i

type setStyleProps = {
  node: HTMLElement
  att: string
  val: string
  style: {}
}

const setStyle = ({ node, att, val, style }: setStyleProps) => {
  style = style || node.style

  if (style) {
    if (val === null || val === '') {
      val = ''
    } else if (!isNaN(Number(val)) && reUnit.test(att)) {
      val += 'px'
    }

    if (att === '') {
      att = 'cssText'
      val = ''
    }

    style[att] = val
  }
}

export const setStyles = (el: HTMLElement, hash: CSSStyleDeclaration) => {
  const hasCSSTextFeature = typeof el.style.cssText !== 'undefined'

  let originStyleText
  const originStyleObj = {}

 hasCSSTextFeature
  ? originStyleText = el.style.cssText
  : originStyleText = el.getAttribute('style')

  originStyleText!.split(';').forEach(item => {
    if (item.indexOf(':') !== -1) {
      const obj = item.split(':')
      originStyleObj[obj[0].trim()] = obj[1].trim()
    }
  })

  const styleObj = {}

  Object.keys(hash).forEach(item => setStyle({
    node: el,
    att: item,
    val: hash[item],
    style: styleObj
  }))

  const mergedStyleObj = Object.assign({}, originStyleObj, styleObj)
  const styleText = Object.keys(mergedStyleObj)
    .map(item => item + ': ' + mergedStyleObj[item] + ';')
    .join(' ')

 hasCSSTextFeature
  ? el.style.cssText = styleText
  : el.setAttribute('style', styleText)
}