1
0

addStyle.js 2.0 KB

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