驗證是否為圖片格式
復制代碼 代碼如下:
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 < digits) {
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 = $("<canvas></canvas>")[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方法了,整理出來,希望小伙伴們能夠喜歡。