js 瀏覽器相容css中webkit、Moz、O、ms…寫法封裝(es6語法)

abcByme發表於2018-09-07
/**
*瀏覽器相容寫法封裝
*/
let elementStyle = document.createElement(`div`).style

let vendor = (() => {
  let transformNames = {
    webkit: `webkitTransform`,
    Moz: `MozTransform`,
    O: `OTransform`,
    ms: `msTransform`,
    standard: `transform`
  }

  for (let key in transformNames) {
    if (elementStyle[transformNames[key]] !== undefined) {
      return key
    }
  }

  return false
})()

export function prefixStyle(style) {
  if (vendor === false) {
    return false
  }

  if (vendor === `standard`) {
    return style
  }

  return vendor + style.charAt(0).toUpperCase() + style.substr(1)
}

//呼叫

const transform = prefixStyle(`transform`)
const backdrop = prefixStyle(`backdrop-filter`)

div.style[transform] = `translate3d(0,0,0)` 等同於  div.style[`transform`] = `translate3d(0,0,0)`

div.style[backdrop] = `blur(4px)`等同於  div.style[`backdrop`] = `blur(4px)`

 

相關文章