Last active
September 6, 2019 09:24
-
-
Save ryu-f/f3bcf94a027e0d3b09075308ded8e272 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment