整理一些最近项目中用到的一些JS方法

验证是否为图片格式

1 function IsImgType(src) {
2     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;
3     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;
4     return rFilter.test(src) || Filter.test(src);
5 }

 

验证是否为颜色

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:

 1 function zero_fill_hex(num, digits) {
 2     var s = num.toString(16);
 3     while (s.length < digits) {
 4         s = "0" + s;
 5     }
 6     return s;
 7 }
 8 
 9 function rgb2hex(rgb) {
10     if (rgb.charAt(0) == ‘#‘) {
11         return rgb;
12     }
13     var ds = rgb.split(/\D+/);
14     var decimal = Number(ds[1]) * 65536 + Number(ds[2]) * 256 + Number(ds[3]);
15     return "#" + zero_fill_hex(decimal, 6);
16 }


验证是否为Email地址:

1 function testEmail (value, target) {
2     value = value.trim();
3     if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value)) {
4         target.val("");
5         alert("Please fill in the correct E-mail address!");
6     }
7 }


将图片src转化为data 64:

 1 function createImgData(img) {
 2     var image = new Image();
 3     image.src = img.src || img;
 4     var tmpCanvas = $("<canvas></canvas>")[0];
 5     var tmpCtx = tmpCanvas.getContext("2d");
 6     if (tmpCanvas) {
 7         tmpCanvas.width = image.width;
 8         tmpCanvas.height = image.height;
 9         tmpCtx.drawImage(image, 0, 0);
10         return tmpCanvas.toDataURL();
11     }
12 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。