首页 > 编程 > JavaScript > 正文

项目中常用的JS方法整理

2019-11-20 13:16:46
字体:
来源:转载
供稿:网友

验证是否为图片格式

复制代码 代码如下:

 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方法了,整理出来,希望小伙伴们能够喜欢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表