驗證是否為圖片格式
function IsImgType(src) {
var rFilter = /^(?:image/bmp|image/cis-cod|image/gif|image/ief|image/jpeg|image/jpeg|image/jpeg|image/pipeg|image/png|image/svg xml |image/tiff|image/x-cmu-raster|image/x-cmx|image/x-icon|image/x-portable-anymap|image/x-portable-bitmap|image/x-portable-graymap|image /x-portable-pixmap|image/x-rgb|image/x-xbitmap|image/x-xpixmap|image/x-xwindowdump)$/i;
var Filter = /(?:bmp|cis-cod|gif|ief|jpeg|jpeg|jpeg|pipeg|png|svg xml|tiff|x-cmu-raster|x-cmx|x-icon|x-portable- anymap|x-portable-bitmap|x-portable-graymap|x-portable-pixmap|x-rgb|x-xbitmap|x-xpixmap|x-xwindowdump)$/i;
return rFilter.test(src) || Filter.test(src);
}
驗證是否為顏色
function detectColor(value) {
var pattern = /^#[0-9a-fA-F]{6}$/; //#XXXXXX
var result;
var rgbRegex = /(^rgb((d ),s*(d ),s*(d ))$)|(^rgba((d ),s*(d ),s*(d )(,s* d .d )*)$)/;
if (pattern.test(value)) {
result = value;
} else if (rgbRegex.test(value)) { //rgba(0, 0, 0, 0)
result = value;
}
return result;
}
將RGB轉換為HEX:
function zero_fill_hex(num, digits) {
var s = num.toString(16);
while (s.length
s = "0" s;
}
return s;
}
function rgb2hex(rgb) {
if (rgb.charAt(0) == '#') {
return rgb;
}
var ds = rgb.split(/D /);
var decimal = Number(ds[1]) * 65536 Number(ds[2]) * 256 Number(ds[3]);
return "#" zero_fill_hex(decimal, 6);
}
驗證是否為Email位址:
function testEmail (value, target) {
value = value.trim();
if (!/^w ([.-]?w )*@w ([.-]?w )*(.w{2,3}) $/.test(value)) {
target.val("");
alert("Please fill in the correct E-mail address!");
}
}
將圖片src轉換為data 64:
function createImgData(img) {
var image = new Image();
image.src = img.src || img;
var tmpCanvas = $("")[0];
var tmpCtx = tmpCanvas.getContext("2d");
if (tmpCanvas) {
tmpCanvas.width = image.width;
tmpCanvas.height = image.height;
tmpCtx.drawImage(image, 0, 0);
return tmpCanvas.toDataURL();
}
}
上面這些就是本人最近專案中所用到的常用的js方法了,整理出來,希望小夥伴們能夠喜歡。