使用工具集
underscore
lodash
xe-utils
计算文本宽度
function calcFontWidth = (str) {
const dom = document.createElement('span');
dom.style = 'display:inline-block;font-size:24px;white-space:no-wrap;';
dom.textContent = str;
document.body.appendChild(dom);
const width = dom.clientWidth;
document.body.removeChild(dom);
return width;
}
色值转换
RGB转换为16进制
String.prototype.colorHex = function () {
var reg = /^(rgb|RGB)/;
var color = this;
if (reg.test(color)) {
var strHex = "#";
var colorArr = color.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
for (var i = 0; i < colorArr.length; i++) {
var hex = Number(colorArr[i]).toString(16);
if (hex === "0") {
hex += hex;
}
strHex += hex;
}
return strHex;
} else {
return String(color);
}
};
"rgb(255,255,255)".colorHex();
16进制转换为RGB
String.prototype.colorRgb = function () {
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
var color = this.toLowerCase();
if (reg.test(color)) {
if (color.length === 4) {
var colorNew = "#";
for (var i = 1; i < 4; i += 1) {
colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
}
color = colorNew;
}
var colorChange = [];
for (var i = 1; i < 7; i += 2) {
colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
}
return "RGB(" + colorChange.join(",") + ")";
} else {
return color;
}
};
"#fff".colorRgb();
"#ffffff".colorRgb();