js常用函数汇总(不定期更新)

时间:2023-03-08 23:22:49
js常用函数汇总(不定期更新)

1、图片按比例压缩

function setImgSize(){
var outbox_w=imgbox.width(),
outbox_h=imgbox.height(); imgbox.find('img').each(function(index, el) {
var obj=$(this),
objH=obj.height(),
objW=obj.width(); if((objH/objW)>(outbox_h/outbox_w)){
obj.css({
height: outbox_h+"px",
width: ((objW/objH)*outbox_h)+"px",
marginLeft:((outbox_w-((objW/objH)*outbox_h))/)+"px"
   });
}else{
obj.css({
width: outbox_w+"px",
height: ((objH/objW)*outbox_w)+"px",
marginTop:((outbox_h-((objH/objW)*outbox_w))/)+"px"
});
}
});
}

2、解析URL上的字符串参数:

function getQueryString(parm){
var reg = new RegExp("(^|&)" + parm + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]);
return null;
}

需要注意的:unescape()函数(找到形式为 %xx 和 %uxxxx 的字符序列(x 表示十六进制的数字),用 Unicode 字符 \u00xx 和 \uxxxx 替换这样的字符序列进行解码,与之对应的是escape()编码),ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。

注意:即便value 中有& 连接符,也没有关系,都可以通过encodeURIComponent进行转码成%26的形式,和浏览器自动拼接的并不冲突,记得decodeURIComponent()解码就好。

3、常用的js校验

3.1 手机号校验

/^(||)?([-]|[]|[]|[-]|[])[-]{}$/

3.2 汉字校验

/^[a-zA-Z\u4e00-\u9fa5]+$/