通用js函数集锦<来源于网络/自己>【一】

1、返回一个全地址
2、cookie
3、验证用户浏览器是否是微信浏览器
4、验证用户浏览器是否是微博内置浏览器
5、query string
6、验证用户设备来源
7、JS验证邮件地址是否合法
8、JS获取字符串长度(区分中英文) 中文算2个字,英文一个
9、检查手机号码是否合法
10、验身份证号码是否正确
11、删除cookie
12、数组是否包函字符串元素
13、后退
14、向上滚动到指定位置
15、判断是否为身份证
16、判断是否为2~15字姓名
17、修复IE中 input 的Placeholder文字显示不正常
18、元素上方弹出提示
19、获取验证码按钮倒数
20、格式化数值,小数点后两位数自动补零
21、预加载图片
22、倒计时
23、微信分享
24、输入框特殊过滤字符过滤
25、对Date的扩展,将 Date 转化为指定格式的String
//返回一个全地址
function resolveUrl(url) {
var a = document.createElement("a");
a.href = url;
return a.href;
} //*************************************************
//* *
//* cookie *
//* *
//*************************************************
function addcookie(name, value, expireHours) {
var cookieString = name + "=" + escape(value);
//判断是否设置过期时间
expireHours = expireHours || 10000; var date = new Date();
date.setTime(date.getTime() + expireHours * 3600 * 1000);
cookieString = cookieString + "; expires=" + date.toGMTString() + "; path=/"; document.cookie = cookieString;
} function getcookie(name) {
var strcookie = document.cookie;
var arrcookie = strcookie.split("; ");
for (var i = 0; i < arrcookie.length; i++) {
var arr = arrcookie[i].split("=");
if (arr[0] == name) return arr[1];
}
return "";
} /**
* 验证用户浏览器是否是微信浏览器
* @author Terence
*
* @return 是微信浏览器返回true否则返回false
*/
function isWeiXinFun(){var ua = window.navigator.userAgent.toLowerCase();if(ua.match(/MicroMessenger/i) == 'micromessenger'){return true;}else{return false;}} /**
* 验证用户浏览器是否是微博内置浏览器
* @author Terence
*
* @return 是微博内置浏览器返回true否则返回false
*/
function isWeibo(){var ua = window.navigator.userAgent.toLowerCase();if(ua.match(/weibo/i) == 'weibo'){return true;}else{return false;}} //*************************************************
//* *
//* query string *
//* *
//************************************************* function getQueryStringByName(name) {
var result = this.location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
if (result == null || result.length < 1) {
return "";
}
return decodeURIComponent(result[1]);
} /**
* 验证用户设备来源
* @author Terence
*
* @return object
*/
function userAgent()
{
var sUserAgent = navigator.userAgent.toLowerCase(); var o = {};
o.isIpad = /ipad/i.test(sUserAgent);
o.isIphone = /iphone os/i.test(sUserAgent);
o.isUc7 = /rv:1.2.3.4/i.test(sUserAgent);
o.isUc = /ucweb/i.test(sUserAgent);
o.isAndroid = /android/i.test(sUserAgent);
o.isWM = /windows mobile/i.test(sUserAgent); o.isPhone = o.isIphone || o.isAndroid || o.isWM || o.isUc7 || o.isUc;
o.isMobile = o.isIpad || o.isPhone || o.isAndroid;
o.isPc = !o.isMobile;
o.isIOS = o.isIpad || o.isIphone; return o;
} /**
* JS验证邮件地址是否合法
* @author Terence
*
* @param email
* @return 合法返回true;不合法返回false
*/
function checkEmail(email){
var re=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
return re.test(email);
} /**
* JS获取字符串长度(区分中英文) 中文算2个字,英文一个
* @author Terence
*
* @param string 电话号码
* @return 返回字符串长度
*/
function getStrLength(str){
var cArr = str.match(/[^\x00-\xff]/ig);
return str.length + (cArr == null ? 0 : cArr.length);
} /**
* 检查手机号码是否合法
* @author Terence
*
* @param string 手机号码
* @return 合法返回true;不合法返回flase
*/
function checkMobile(string){
return (/^1[3-9]+\d{9}$/.test(string));
} /**
* 验身份证号码是否正确
* @author Terence
*
* @param num 身份证号码
* @return 合法返回true;不合法返回flase
*/
function isIdCardNo(num){
var factorArr = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);
var error;
var varArray = new Array();
var intValue;
var lngProduct = 0;
var intCheckDigit;
var intStrLen = num.length;
var idNumber = num;
// initialize
if ((intStrLen != 15) && (intStrLen != 18)) {
//error = "输入身份证号码长度不对!";
//alert(error);
//frmAddUser.txtIDCard.focus();
return false;
}
// check and set value
for(i=0;i<intStrLen;i++) {
varArray[i] = idNumber.charAt(i);
if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
//error = "错误的身份证号码!.";
//alert(error);
//frmAddUser.txtIDCard.focus();
return false;
} else if (i < 17) {
varArray[i] = varArray[i]*factorArr[i];
}
}
if (intStrLen == 18) {
//check date
var date8 = idNumber.substring(6,14);
if (IsDate(date8) == false) {
//error = "身份证中日期信息不正确!.";
//alert(error);
return false;
}
// calculate the sum of the products
for(i=0;i<17;i++) {
lngProduct = lngProduct + varArray[i];
}
// calculate the check digit
intCheckDigit = 12 - lngProduct % 11;
switch (intCheckDigit) {
case 10:
intCheckDigit = 'X';
break;
case 11:
intCheckDigit = 0;
break;
case 12:
intCheckDigit = 1;
break;
}
// check last digit
if (varArray[17].toUpperCase() != intCheckDigit) {
//error = "身份证效验位错误!正确为: " + intCheckDigit + ".";
//alert(error);
return false;
}
}
else{ //length is 15
//check date
var date6 = "19"+idNumber.substring(6,12);
if (IsDate(date6) == false) {
//alert("身份证日期信息有误!.");
return false;
}
}
//alert ("Correct.");
return true;
}
//删除cookie
function delCookie(name){
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getcookie(name);
if(cval!=null) document.cookie= name + "="+cval+"; path=/;expires="+exp.toGMTString();
}
//数组是否包函字符串元素
function contains(arr, str) {
var i = arr.length;
while (i--) {
if (arr[i] === str) {
return true;
}
}
return false;
}
/*后退*/
function goback() {
window.history.go(-1);
} /*向上滚动到指定位置*/
function click_scroll(e) {
var scroll_offset = $(e).offset();
$("body,html").animate({
scrollTop:scroll_offset.top - 10
},0);
}
/*判断是否为身份证*/
function isIdCardNo(num) {
var num = num.toUpperCase(),
len = num.length,
re;
if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
return false;
}
else {
if (len == 15) {
re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
splitArr = num.match(re);
//检查生日日期是否正确 如19850843 或者 20000843
var dtmBirth = new Date('19' + splitArr[2] + '/' + splitArr[3] + '/' + splitArr[4]);
if (!((dtmBirth.getYear() == Number(splitArr[2])) && ((dtmBirth.getMonth() + 1) == Number(splitArr[3])) && (dtmBirth.getDate() == Number(splitArr[4])))) {
//alert('输入的身份证号里出生日期不对!');
return false;
}
else {
return true;
}
}
else if (len == 18) {
re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
var splitArr = num.match(re);
var dtmBirth = new Date(splitArr[2] + "/" + splitArr[3] + "/" + splitArr[4]);
if (!((dtmBirth.getFullYear() == Number(splitArr[2])) && ((dtmBirth.getMonth() + 1) == Number(splitArr[3])) && (dtmBirth.getDate() == Number(splitArr[4])))) {
//alert('输入的身份证号里出生日期不对!');
return false;
}
//检验18位身份证的校验码是否正确。
//校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
var checkNum;
var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
var nTemp = 0, i;
for (i = 0; i < 17; i++) {
nTemp += num.substr(i, 1) * arrInt[i];
}
checkNum = arrCh[nTemp % 11];
if (checkNum != num.substr(17, 1)) {
//alert('18位身份证的校验码不正确!应该为:' + checkNum);
return false;
}
else {
return true;
}
} }
} /*判断是否为2~15字姓名*/
function isChineseName(name) {
reg = /^[\u4E00-\u9FA5]{2,15}$/;
if (!reg.test(name)) {
return false;
} else {
return true;
}
} /**
* nelson
* 20150810
* 修复IE中 input 的Placeholder文字显示不正常
*/
function fixedIePlaceholder() {
var placeholderfriend = {
focus: function (s) {
s = $(s).hide().prev().show().focus();
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue.replace("placeholderfriend", ""));
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue.replace("placeholderfriend", ""));
}
}
}
//判断是否支持placeholder
function isPlaceholer() {
var input = document.createElement('input');
return "placeholder" in input;
}
//不支持的代码
if (!isPlaceholer()) {
$(function () {
var form = $(this);
//遍历所有文本框,添加placeholder模拟事件
var elements = form.find("input[type='text'][placeholder]");
elements.each(function () {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (pValue) {
if (sValue == '') {
s.val(pValue);
}
}
});
elements.focus(function () {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (sValue && pValue) {
if (sValue == pValue) {
s.val('');
}
}
});
elements.blur(function () {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (!sValue) {
s.val(pValue);
}
});
//遍历所有密码框,添加placeholder模拟事件
var elementsPass = form.find("input[type='password'][placeholder]");
elementsPass.each(function (i) {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (pValue) {
if (sValue == '') {
//DOM不支持type的修改,需要复制密码框属性,生成新的DOM
var html = this.outerHTML || "";
html = html.replace(/\s*type=(['"])?password\1/gi, " type=text placeholderfriend")
.replace(/\s*(?:value|on[a-z]+|name)(=(['"])?\S*\1)?/gi, " ")
.replace(/\s*placeholderfriend/, " placeholderfriend value='" + pValue
+ "' " + "onfocus='placeholderfriendfocus(this);' ");
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue + "placeholderfriend");
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue + "placeholderfriend");
}
s.hide();
s.after(html);
}
}
});
elementsPass.blur(function () {
var s = $(this);
var sValue = s.val();
if (sValue == '') {
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue + "placeholderfriend");
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue + "placeholderfriend");
}
s.hide().next().show();
}
});
});
}
window.placeholderfriendfocus = placeholderfriend.focus;
}
/*****
元素上方弹出提示,详见css与html
example showTips("btn", '请输入手机号码', 3);
*******/
function showTips(o, msg, wait) {
em = $(o).parent("li");
if (wait == 0) {
em.find(".tips").hide();
} else {
if(wait == 3)
{
em.find(".tips").remove();
$('<div class="tips ui-corner"><p><em>◆</em>'+msg+'</p></div>').appendTo(em);
$(".tips").css({'margin-left':($(".tips").width()/2) * (-1)});
}
wait--;
setTimeout(function() {
showTips(o, msg, wait)
},
1000);
}
} /***
获取验证码按钮倒数
example timer("btn", 60);
*******/
function timer(o, wait) {
if (wait == 0) {
o.removeAttr("disabled");
o.removeClass("ui-btn-disabled");
o.val("重新发送");
wait = 60;
} else {
o.attr("disabled", true);
o.addClass("ui-btn-disabled");
o.val(" " + wait + "秒 ");
wait--;
setTimeout(function() {
timer(o, wait)
},
1000)
}
}
.ui-form li {
padding: 10px 25px;
height: 30px;
position: relative;
margin: 0 7px;
border-bottom: 1px solid #e2e2e2;
}
.ui-form li .tips {
position: absolute;
top: -33px;
left: 50%;
height: 22px;
line-height: 22px;
padding: 0 10px;
font-size: 11px;
padding: 5px;
color: #FFF;
display: inline-block;
background: #323232;
width: 150px;
text-align: center;
}

.ui-corner {
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
}

<li><input type="password" name="password" class="ui-input-text ui-corner" id="PASSWORD" onblur="isPassword(this);" placeholder="密码"></li>
//格式化数值,小数点后两位数自动补零
function formatNum(number) {
var f = parseFloat(number);
if (isNaN(f)) {
return false;
}
var f = Math.round(number * 100) / 100;
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
return s;
}
//预加载图片
function preLoadImages(urls) {//可以是String Array或者String
var argsLen = arguments.length,
loadImage = function (url) {
var img = new Image();
img.src = url;
};
if (argsLen == 1) {
if (typeof (urls) == "string" && (sLen = urls.length) > 1) {//预加载一个图片
loadImage(urls);
}
else if (Object.prototype.toString.call(arguments[0]) == "[object Array]" && urls.length > 0) {//预加载多个图片
for (var i = 0; i < urls.length; i++) {
loadImage(urls[i]);
}
}
}
}
/****
闪购商品详细页倒计时函数
time 2015/10/1 10:00:00
id 元素
example countDown("#colockbox1");
<span data-nowtime="2015/10/22 17:57:52" data-starttime="2015/10/22 18:57:52" data-endtime="2015/10/23 17:59:52" id="colockbox1"></span>
****/
function countDown(obj, data_nowtime) {
var COMING = 0,
ACTIVE = 1,
DISABLED = -1;
var This = $(obj),
ntime = data_nowtime,
stime = This.attr("data-starttime"),
etime = This.attr("data-endtime"),
day_elem = This.find('.day').html("/天"),
hour_elem = This.find('.hour').html("/小时"),
minute_elem = This.find('.minute').html("/分"),
second_elem = This.find('.second').html("/秒");
var now_time = new Date(ntime).getTime(),
start_time = new Date(stime).getTime(),
end_time = new Date(etime).getTime(),
status = DISABLED;
if (now_time < start_time) {
This.find(".coming").show();
$("#buynow").addClass("disabled").attr("value", "即将开抢").attr("disabled", "disabled");
$("#addtocart").addClass("disabled").attr("disabled", "disabled");
end_time = start_time;
status = COMING;
} else if (now_time >= start_time && now_time < end_time) {
This.find(".coming").hide();
This.find(".due").show();
status = ACTIVE;
} else {
This.remove();
status = DISABLED;
return;
}
var sys_second = (end_time - now_time) / 1000;
var timer = setInterval(function () {
if (sys_second >= 1) {
sys_second -= 1;
var day = Math.floor((sys_second / 3600) / 24);
var hour = Math.floor((sys_second / 3600) % 24);
var minute = Math.floor((sys_second / 60) % 60);
var second = Math.floor(sys_second % 60);
if (parseInt(day) > 0) {
day_elem.text(day + '天');
hour_elem.text((hour < 10 ? "0" + hour : hour) + '小时');//计算小时
minute_elem.text((minute < 10 ? "0" + minute : minute) + '分');//计算分钟
second_elem.text((second < 10 ? "0" + second : second) + '秒');//计算秒杀
} else {
day_elem.text("0" + '天');
hour_elem.text((hour < 10 ? hour : hour) + '小时');
minute_elem.text((minute < 10 ? "0" + minute : minute) + '分');//计算分钟
second_elem.text((second < 10 ? "0" + second : second) + '秒');//计算秒杀
}
} else {
clearInterval(timer);
if (status == COMING) {
$("#buynow").removeClass("disabled").attr("value", "立即购买").attr("disabled", false);
$("#addtocart").removeClass("disabled").attr("disabled", false);
countDown(obj, stime);
}
if (status == ACTIVE) {
$("#buynow").addClass("disabled").attr("value", "已结束").attr("disabled", "disabled");
$("#addtocart").addClass("disabled").attr("disabled", "disabled");
status == DISABLED;
This.remove();
}
}
}, 1000);
}
function wechatShareData(img,url,title,desc)
{
try {
wx.ready(function () {
var data = {"img":img, "url":url, "title":title, "desc":desc};
wechatShare(data);
});
}catch(e) {
}
}
//输入框特殊过滤字符过滤
function filtInputValue(input) {
var pattern = new RegExp("[%--`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——| {}【】‘’;:”“\"'。,、?]"); //格式 RegExp("[在中间定义特殊过滤字符]")
var s = input.value;
var rs = "";
for (var i = 0; i < s.length; i++) {
rs = rs + s.substr(i, 1).replace(pattern, '');
}
input.value = rs;
}
       // 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.format = function (fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
04-25 06:53