index.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * FeHelper 颜色转换工具
  3. */
  4. new Vue({
  5. el: '#containerColor',
  6. data: {
  7. fromHEX: '#43ad7f7f',
  8. toRGB: '',
  9. fromRGB: 'rgba(190,20,128,0.5)',
  10. toHEX: ''
  11. },
  12. mounted: function () {
  13. // 初始化颜色转换
  14. this.colorHexToRgb();
  15. this.colorRgbToHex();
  16. },
  17. methods: {
  18. colorHexToRgb: function () {
  19. let hex = this.fromHEX.trim().replace(/^#/, '');
  20. let rgb = [];
  21. switch (hex.length) {
  22. case 3:
  23. case 4:
  24. rgb.push(parseInt(hex[0] + '' + hex[0], 16).toString(10)); // r
  25. rgb.push(parseInt(hex[1] + '' + hex[1], 16).toString(10)); // g
  26. rgb.push(parseInt(hex[2] + '' + hex[2], 16).toString(10)); // b
  27. hex.length === 4 && rgb.push((parseInt(parseInt(hex[3] + '' + hex[3], 16).toString(10)) / 256).toFixed(2)); // a
  28. break;
  29. case 6:
  30. case 8:
  31. rgb.push(parseInt(hex[0] + '' + hex[1], 16).toString(10)); // r
  32. rgb.push(parseInt(hex[2] + '' + hex[3], 16).toString(10)); // g
  33. rgb.push(parseInt(hex[4] + '' + hex[5], 16).toString(10)); // b
  34. hex.length === 8 && rgb.push((parseInt(parseInt(hex[6] + '' + hex[7], 16).toString(10)) / 256).toFixed(2)); // a
  35. break;
  36. }
  37. if (rgb.length === 3) {
  38. this.toRGB = 'rgb(' + rgb.join(', ') + ')';
  39. } else if (rgb.length === 4) {
  40. this.toRGB = 'rgba(' + rgb.join(', ') + ')';
  41. } else {
  42. this.toRGB = '';
  43. }
  44. },
  45. colorRgbToHex: function () {
  46. let rgb = this.fromRGB.trim().replace(/\s+/g, '').replace(/[^\d,\.]/g, '').split(',').filter(n => {
  47. return n.length && parseInt(n, 10) <= 255;
  48. });
  49. let hex = [];
  50. if (rgb.length === 3 || rgb.length === 4) {
  51. hex.push(parseInt(rgb[0], 10).toString(16).padStart(2, '0')); // r
  52. hex.push(parseInt(rgb[1], 10).toString(16).padStart(2, '0')); // g
  53. hex.push(parseInt(rgb[2], 10).toString(16).padStart(2, '0')); // b
  54. rgb.length === 4 && hex.push(Math.floor(parseFloat(rgb[3], 10) * 255).toString(16).padStart(2, '0')); // a
  55. }
  56. if (hex.length) {
  57. this.toHEX = '#' + hex.join('');
  58. } else {
  59. this.toHEX = '';
  60. }
  61. }
  62. }
  63. });