You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

addStyle.js 1.6KB

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