addStyle.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import test from './test.js'
  2. import trim from './trim.js'
  3. /**
  4. * @description 样式转换
  5. * 对象转字符串,或者字符串转对象
  6. * @param {object | string} customStyle 需要转换的目标
  7. * @param {String} target 转换的目的,object-转为对象,string-转为字符串
  8. * @returns {object|string}
  9. */
  10. function addStyle(customStyle, target = 'object') {
  11. // 字符串转字符串,对象转对象情形,直接返回
  12. if (test.empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' &&
  13. typeof(customStyle) === 'string') {
  14. return customStyle
  15. }
  16. // 字符串转对象
  17. if (target === 'object') {
  18. // 去除字符串样式中的两端空格(中间的空格不能去掉,比如padding: 20px 0如果去掉了就错了),空格是无用的
  19. customStyle = trim(customStyle)
  20. // 根据";"将字符串转为数组形式
  21. const styleArray = customStyle.split(';')
  22. const style = {}
  23. // 历遍数组,拼接成对象
  24. for (let i = 0; i < styleArray.length; i++) {
  25. // 'font-size:20px;color:red;',如此最后字符串有";"的话,会导致styleArray最后一个元素为空字符串,这里需要过滤
  26. if (styleArray[i]) {
  27. const item = styleArray[i].split(':')
  28. style[trim(item[0])] = trim(item[1])
  29. }
  30. }
  31. return style
  32. }
  33. // 这里为对象转字符串形式
  34. let string = ''
  35. for (const i in customStyle) {
  36. // 驼峰转为中划线的形式,否则css内联样式,无法识别驼峰样式属性名
  37. const key = i.replace(/([A-Z])/g, '-$1').toLowerCase()
  38. string += `${key}:${customStyle[i]};`
  39. }
  40. // 去除两端空格
  41. return trim(string)
  42. }
  43. export default addStyle