1、判斷瀏覽器的innerText或textContent屬性
function setcontent(element,content){
if(typeof element.innerText === "string"){
return element.innerText = content;
}else {
return element.textContent = content;
}
};
2、獲取頁面的當中可視區域的寬高度的兼容函數
function getClient(){
return {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0
}
};
3、獲取下一個兄弟元素的兼容函數
function getEleSibling(element){
if(element.nextElementSibling){
return element.nextElementSibling;
}else {
var next = element.nextSibling;
while(next && next.nodeType !== 1){
next = next.nextSibling
}
return next;
}
};
4、獲取上一個兄弟元素的兼容函數
function setprev(element){
if(element.previousElementSibling){
return element.previousElementSibling;
}else {
var prev = element.previousSibling;
while(prev && prev.nodeType !== 1){
prev = prev.previousSibling;
}
return prev;
};
};
5、獲取類名的兼容函數
function getClassName(ele,className){
if(ele.getElementsByClassName){
return ele.getElementsByClassName(className);
}else {
var elements = ele.getElementsByTagName("*");
var arr = [];
for (var i = 0; i < elements.length; i++) {
if(elements[i].className.indexOf(className) !== -1){
arr.push(elements[i]);
}
}
return arr;
}
};
6、勻速動畫的封裝函數
function animate(Obj,target){
clearInterval(Obj.timer);
Obj.timer = setInterval(function(){
var leader = Obj.offsetLeft,
step = 10,
step = leader < target ? step : -step;
if(Math.abs(leader - target) > Math.abs(step)){
Obj.style.left = leader + step + "px";
}else {
Obj.style.left = target + "px";
clearInterval(Obj.timer);
}
},15)
};
7、獲取頁面被捲去的頭部高度和左側寬度的 兼容函數
function scroll(){
return {
top : window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
left : window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0
}
};
9、獲取外部樣式的兼容函數
function getStyle(obj,attr){
if(window.getComputedStyle){
return window.getComputedStyle(obj,null)[attr];
}else {
return obj.currentStyle[attr];
}
};
10、用緩動動畫封裝一個回調函數(包含透明度和層級)
function setanimate3(obj,josn,fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var flag = true;
for(var key in josn){
if(key === "opacity"){
var leader = getStyle(obj,key) * 100;
var step = (josn[key] * 100 - leader) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style[key] = (leader + step) / 100;
}else if(key === "zIndex"){
obj.style[key] = josn[key];
}else {
var leader = parseInt(getStyle(obj,key)) || 0;
var step = (josn[key] - leader) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style[key] = leader + step + "px";
}
if(josn[key] !== leader){
flag = false;
}
}
if(flag){
clearInterval(obj.timer);
if(fn){
fn();
}
}
},15)
};
function getStyle(obj,attr){
if(window.getComputedStyle){
return window.getComputedStyle(obj,null)[attr];
}else {
return obj.currentStyle[attr];
}
};
11、設置全屏的能力檢測
btn1.onclick=function(){
//全屏
if(div.requestFullScreen){
div.requestFullScreen();
}else if(div.webkitRequestFullScreen){
div.webkitRequestFullScreen();
}else if(div.mozRequestFullScreen){
div.mozRequestFullScreen();
}else if(div.msRequestFullScreen){
div.msRequestFullScreen();
} else if(div.oRequestFullScreen){
div.oRequestFullScreen();
}
};
btn2.onclick=function(){
//退出全屏
if(document.cancelFullScreen){
document.cancelFullScreen();
}else if(document.webkitCancelFullScreen){
document.webkitCancelFullScreen();
}else if(document.mozCancelFullScreen){
document.mozCancelFullScreen();
}else if(document.msCancelFullScreen){
document.msCancelFullScreen();
}else if(document.oCancelFullScreen){
document.oCancelFullScreen();
}
};
btn3.onclick=function(){
//檢測是否全屏
if(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || document.oFullscreenElement){
alert(true);
}else {
alert(false);
}
};
12、拖拽任意元素
//被拖拽元素
document.ondragstart = function(event){
event.dataTransfer.setData("text/html",event.target.id);
};
//目標元素
document.ondragover = function(event){
event.preventDefault();
};
document.ondrop = function(event){
var x = event.dataTransfer.getData("text/html");
event.target.appendChild(document.getElementById(x));
};
13、模擬jquery的ajax請求文件(跨域(jsonp)和不跨域(json)。
function ajax(obj){
var defaus = {
type:"get",
url:"#",
async:true,
data:{},
jsonp:"callback",
dataType:"text",
success:function(data){
console.log(data);
}
};
for(var key in obj){
defaus[key] = obj[key];
};
if(defaus.dataType === "jsonp"){
ajaxJsonp(defaus);
}else {
ajaxJson(defaus);
};
function ajaxJsonp(){
var cbName = "jQuery" + ("1.11.1" + Math.random()).replace(/\D/g,"") + "_" + (new Date().getTime());//這裏是設置的默認的回調函數名字
if(defaus.jsonpCallback){//這裏是爲了方便設置jsonp的默認名字
cbName = defaus.jsonpCallback;
};
window[cbName] = function(data){//這裏就是回調函數,調用方式服務器響應內容來調用,實際上時向window中添加了一個方法,方法名是變量cbname的值
try {//用try---finally將請求完數據的script標籤從頁面中刪除
defaus.success(data);//這裏的data是實參
}finally{
script.parentNode.removeChild(script);//將請求數據後的script標籤刪除
delete window[cbName];//將添加在window上的自定義方法刪除
}
};
var parm = "";
for(var key in defaus.data){
parm += key + "=" + defaus.data[key] + "&";
};
if(parm){
parm += parm.substring(0,parm.length - 1);
parm = "&" + parm;
};
var script = document.createElement("script");
script.src = defaus.url + "?" + defaus.jsonp + "=" + cbName + parm;
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
};
function ajaxJson(){
var xhr;
if(window.XMLHttpRequest){//處理兼容Ajax請求
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
};
var parm = "";//將對象形式的參數(實參)轉爲字符串,
for(var key in defaus.data){//這裏是用來將(get請求後邊要傳入的鍵值對)中的值賦值給parm
parm += key + "=" + defaus.data[key] + "&";
};
if(parm){//如果parm中有值,則將其提取出來,目的是爲了去掉最後一個多餘的&符號
parm = parm.substring(0,parm.length-1);//從0開始截取,截取到最後一個值也可使用substring()方法
};
if(defaus.type === "get"){//處理get參數
defaus.url += "?"+ encodeURI(parm);//這裏是爲了防止中文亂碼的問題。
};
xhr.open(defaus.type,defaus.url,defaus.async);//設置發送參數
var code = null;
if(defaus.type === "post"){//處理post參數,且必須設置頭信息
code = parm;
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
xhr.send(code);//執行發送動作
//處理同步請求,注意,同步的話就不使用回調函數了
if(!defaus.async){
if(defaus.dataType === "json"){
return JSON.parse(xhr.responseText);
}else {
return xhr.responseText;
};
};
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
var data = xhr.responseText;
if(defaus.dataType === "json"){
data = JSON.parse(data);//注意:使用此方法要引入json.js包(爲了適應IE和舊版瀏覽器);
};
defaus.success(data);
};
};
};
}
};
14、獲取URL地址欄。
//方法一:正則
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //獲取url中"?"符後的字符串並正則匹配
var context = "";
if (r != null)
context = r[2];
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "" : context;
};
//方法二:
function getSearchString(key) {//key就是要截取的參數的鍵
// 獲取URL中?之後的字符
var str = location.search;
str = str.substring(1,str.length);
// 以&分隔字符串,獲得類似name=xiaoli這樣的元素數組
var arr = str.split("&");
var obj = new Object();
// 將每一個數組元素以=分隔並賦給obj對象
for(var i = 0; i < arr.length; i++) {
var tmp_arr = arr[i].split("=");
obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
}
return obj[key];
};
//方法三:
function getQueryString(name) {
try {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var url = location.href.split("?");
r = url[1].match(reg);
if (r != null) return unescape(r[2]);
return "";
} catch (e) {
return "";
}
};
15、獲取當前日期信息
function getDayTime() {
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var date = d.getDate();
var day = d.getDay();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if (h < 10) { h = "0" + h; }
if (m < 10) { m = "0" + m; }
if (s < 10) { s = "0" + s; }
var week = ["日", "一", "二", "三", "四", "五", "六"];
//var str = year + "年" + month + "月" + date + "日 星期" + week[day] + " " + h + ":" + m + ":" + s;
var str = year + "年" + month + "月" + date + "日 星期" + week[day] + " " + h + ":" + m;
return str;
};
16、按出生日期算年齡
function birthDataChangeAge(date) {
if (date == "" || date == undefined) {
return "";
}
var r = date.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
var d = new Date(r[1], r[3] - 1, r[4]);
if (r == null) {
return false;
}
else if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
var Y = new Date().getFullYear();
return (Y - r[1]);
}
else {
return false;
}
};
17、18位身份證號驗證
function isIdCard(idcard) {
if (idcard.length != 18) {
return false
}
var num = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var total = 0;
for (i = 0; i < 17; i++) {
total = total + Number(idcard.substring(i, i + 1)) * num[i];
}
var mod = total % 11;
var charx = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
if (idcard.substring(17, 18).toUpperCase() == charx[mod]) {
console.log("身份證號正確");
return true;
} else {
console.log("身份證號錯誤");
return false
}
};
18、cookie設置,存取,刪除
//設置cookie
function setCookie(name, value, seconds) {
seconds = seconds || 0; //seconds有值就直接賦值,沒有爲0,這個根php不一樣。
var expires = "";
if (seconds != 0) { //設置cookie生存時間
var date = new Date();
date.setTime(date.getTime() + (seconds * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + escape(value) + expires + "; path=/"; //轉碼並賦值
};
//取得cookie
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';'); //把cookie分割成組
for (var i = 0; i < ca.length; i++) {
var c = ca[i]; //取得字符串
while (c.charAt(0) == ' ') { //判斷一下字符串有沒有前導空格
c = c.substring(1, c.length); //有的話,從第二位開始取
}
if (c.indexOf(nameEQ) == 0) { //如果含有我們要的name
return unescape(c.substring(nameEQ.length, c.length)); //解碼並截取我們要值
}
}
return false;
};
//清除cookie
function clearCookie(name) {
setCookie(name, "", -1);
};
19、MD5加密
function md5(sMessage) {
function RotateLeft(lValue, iShiftBits) { return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); }
function AddUnsigned(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
}
else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
}
else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x, y, z) { return (x & y) | ((~x) & z); }
function G(x, y, z) { return (x & z) | (y & (~z)); }
function H(x, y, z) { return (x ^ y ^ z); }
function I(x, y, z) { return (y ^ (x | (~z))); }
function FF(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function GG(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function HH(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function II(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function ConvertToWordArray(sMessage) {
var lWordCount;
var lMessageLength = sMessage.length;
var lNumberOfWords_temp1 = lMessageLength + 8;
var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (sMessage.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
}
function WordToHex(lValue) {
var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
}
return WordToHexValue;
}
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d
var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
x = ConvertToWordArray(sMessage);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a; BB = b; CC = c; DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = AddUnsigned(a, AA); b = AddUnsigned(b, BB);
c = AddUnsigned(c, CC); d = AddUnsigned(d, DD);
}
var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
return temp.toUpperCase();
};
20、常用正則驗證
function regNum(number){
return /[\u4e00-\u9fa5]/.test(number);//密碼不能輸入中文
};
function regIDcard(regIDcard){
return /(^\d{18}$)|(^\d{17}(\d|[Xx])$)/.test(regIDcard);//身份證號爲字符和數字且爲18位
};
function regPhone(regPhone){
return /^1[34578]\d{9}$/.test(regPhone);//手機號碼驗證
};
function regNumsz(code){
return /^\d{4}$/.test(code);//驗證碼爲純數字
}
function regName() {
return /^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$|^[\u4E00-\u9FA5A-Za-z]+$|^[A-Za-z]+(·[A-Za-z]+)*$/.test(name);//姓名只能輸入漢字或者英文
};
function regEmail() {
return /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;//郵箱格式驗證
};
21、驗證碼倒計時
function YZTimeOut() {
$("#phonenum").attr("disabled", true);
lgmsgOutTime = null;
var lgmsgTime = 60;
//驗證碼倒計時;
if (!lgmsgOutTime) {
lgmsgOutTime = setInterval(function () {
if (lgmsgTime > 0) {
lgmsgTime--;
$("#plg_timeout").html(lgmsgTime);
} else {
clearInterval(lgmsgOutTime);
lgmsgTime = 60;
$("#plg_timeout").html(lgmsgTime);
$("#phonenum").removeAttr("disabled");
lgmsgOutTime = null;
}
}, 1000);
}
};
//登錄驗證碼復原(登陸成功後操作)
function YzmLgReset() {
clearInterval(lgmsgOutTime);
var lgmsgTime = 60;
$("#plg_timeout").html(lgmsgTime);
$("#plg_SendCode").show();
$("#plg_CountDown").hide();
$("#phonenum").removeAttr("disabled");
lgmsgOutTime = null;
};
22、判斷是ios還是安卓系統(瀏覽器用)
function IsIos() {
var u = navigator.userAgent, app = navigator.appVersion;
//蘋果
if (u.indexOf('AppleWebKit') > -1 && u.indexOf('MicroMessenger') > -1 && u.indexOf('iPhone') > -1 && !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
return true;
} else {
//安卓
return false;
};
};
23、社會統一信用代碼校驗
function CheckCreditCode(creditCode, isSubtle) {
if (creditCode == null || creditCode == undefined || creditCode == "") return false;
if (isSubtle != false) isSubtle = true;
if (!isSubtle) creditCode = creditCode.toUpperCase();
var Ancode, Ancodevalue, total = 0;
var weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];//權
var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
for (var i = 0; i < creditCode.length - 1; i++) {
Ancode = creditCode.substring(i, i + 1);
Ancodevalue = str.indexOf(Ancode);
total = total + Ancodevalue * weightedfactors[i];
}
var logiccheckcode = 31 - total % 31;
if (logiccheckcode == 31) {
logiccheckcode = 0;
}
var Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
var Array_Str = Str.split(',');
logiccheckcode = Array_Str[logiccheckcode];
var checkcode = creditCode.substring(17, 18);
return logiccheckcode == checkcode;
};
24、營業執照註冊號校驗
function CheckRegCode(regCode) {
var result = -1;
if (regCode.length > 1) {
var ti = 0, si = 0, cj = 0, pj = 10;
for (var i = 0; i < regCode.length; i++) {
ti = parseInt(regCode.substring(i, i + 1));
si = pj + ti;
cj = (0 == si % 10 ? 10 : si % 10) * 2;
pj = (cj % 11) == 0 ? 10 : (cj % 11);
if (i == regCode.length - 1) {
if (regCode.length == 14) {
pj = (cj % 11) == 0 ? 10 : (cj % 11);
result = 1 - pj < 0 ? 11 - pj : 1 - pj;
} else if (regCode.length == 15) {
result = si % 10;
}
}
}
}
return result == 1;
};
25、組織機構代碼校驗
function CheckOrgCode(orgCode, isSubtle) {
if (orgCode == null || orgCode == undefined || orgCode == "") return false;
if (isSubtle != false) isSubtle = true;
if (!isSubtle) orgCode = orgCode.toUpperCase();
var ws = [3, 7, 9, 10, 5, 8, 4, 2];
var str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//判斷是否有“-”,如果沒有則添加“-”
var aaa = orgCode.slice(orgCode.length - 2, orgCode.length - 1);
if(aaa != "-"){
orgCode = orgCode.slice(0, orgCode.length - 1) + "-" + orgCode.slice(orgCode.length - 1);
};
if (!/^([0-9A-Z]){8}-[0-9|X]$/.test(orgCode)) return false;
var sum = 0;
for (var i = 0; i < 8; i++) {
var c = orgCode.substring(i, i + 1);
//var c = orgCode.ToCharArray()[i];
sum += str.indexOf(c) * ws[i];
}
var c9 = 11 - (sum % 11);
var sc9 = c9 + "";
if (11 == c9) {
sc9 = "0";
} else if (10 == c9) {
sc9 = "X";
}
var oc = orgCode.substring(9, 10);
return sc9 == oc;
};
26、循環獲取二級字典
function getEjVal(dictory, ids) {
if (ids != "" && ids != null && ids != undefined) {
var arr = ids.split(",");
var empty = [];
$.each(dictory, function (i, item) {
var childs = item.children;
//二級循環
$.each(childs, function (i, item) {
for (var k = 0; k < arr.length; k++) {
if (item.id == arr[k]) {
empty.push(item.value);
};
};
});
});
//console.log(empty);
return empty.join(",");
};
};
27、循環獲取三級字典
function getThreeDicoy(dictory,ids) {
//一項
if (ids != undefined && ids != "" && ids != null) {
var idsArr = ids.split(",");
var empty = [];
//一級循環
for (var i = 0; i < dictory.length; i++) {
var ejChilds = dictory[i].children;
//二級循環
for (var j = 0; j < ejChilds.length; j++) {
var sjChilds = ejChilds[j].children;
//三級循環
for (var k = 0; k < sjChilds.length; k++) {
//循環傳過來的ID
for (var m = 0; m < idsArr.length; m++) {
if (idsArr[m] == sjChilds[k].id) {
empty.push(sjChilds[k].value);
};
};
};
};
};
return empty.join(",");
};
};
28、兼容ie初始選擇框和input框(placeholder提示)
function InitPlaceholder() {
$("select").each(function () {
if ($(this).val() == "" || $(this).val() == null) {
$(this).css({ "color": "#999999" });
} else if ($(this).val() == $(this).attr("placeholder")) {
$(this).css({ "color": "#999999" });
} else {
$(this).css({ "color": "#454545" });
}
});
$("select").change(function () {
if ($(this).val() == "") {
$(this).css({ "color": "#999999" });
} else if ($(this).val() == $(this).attr("placeholder")) {
$(this).css({ "color": "#999999" });
} else {
$(this).css({ "color": "#454545" });
}
});
$("input:button").each(function () {
if ($(this).val() == "") {
$(this).val($(this).attr("placeholder"))
$(this).css({ "color": "#999999" });
} else if ($(this).val() == $(this).attr("placeholder")) {
$(this).css({ "color": "#999999" });
} else {
$(this).css({ "color": "#454545" });
}
});
$("input:button").change(function () {
if ($(this).val() == "") {
$(this).val($(this).attr("placeholder"))
$(this).css({ "color": "#999999" });
} else if ($(this).val() == $(this).attr("placeholder")) {
$(this).css({ "color": "#999999" });
} else {
$(this).css({ "color": "#454545" });
}
});
};
29.判斷是pc還是移動
function IsPC() {
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"];
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
};
/**
* 計算年齡(根據出生日期)
* 計算年份->計算月份->計算天數
*/
function getDiffYmdBetweenDate(sDate1,sDate2){
var fixDate = function(sDate){
var aD = sDate.split('-');
for(var i = 0; i < aD.length; i++){
aD[i] = fixZero(parseInt(aD[i]));
}
return aD.join('-');
};
var fixZero = function(n){
return n < 10 ? '0'+n : n;
};
var fixInt = function(a){
for(var i = 0; i < a.length; i++){
a[i] = parseInt(a[i]);
}
return a;
};
var getMonthDays = function(y,m){
var aMonthDays = [0,31,28,31,30,31,30,31,31,30,31,30,31];
if((y%400 == 0) || (y%4==0 && y%100!=0)){
aMonthDays[2] = 29;
}
return aMonthDays[m];
};
var checkDate = function(sDate){
};
var y = 0;
var m = 0;
var d = 0;
var sTmp;
var aTmp;
sDate1 = fixDate(sDate1);
sDate2 = fixDate(sDate2);
if(sDate1 > sDate2){
sTmp = sDate2;
sDate2 = sDate1;
sDate1 = sTmp;
}
var aDate1 = sDate1.split('-');
aDate1 = fixInt(aDate1);
var aDate2 = sDate2.split('-');
aDate2 = fixInt(aDate2);
//計算相差的年份
/*aTmp = [aDate1[0]+1,fixZero(aDate1[1]),fixZero(aDate1[2])];
while(aTmp.join('-') <= sDate2){
y++;
aTmp[0]++;
}*/
y = aDate2[0] - aDate1[0];
if( sDate2.replace(aDate2[0],'') < sDate1.replace(aDate1[0],'')){
y = y - 1;
}
//計算月份
aTmp = [aDate1[0]+y,aDate1[1],fixZero(aDate1[2])];
while(true){
if(aTmp[1] == 12){
aTmp[0]++;
aTmp[1] = 1;
}else{
aTmp[1]++;
}
if(([aTmp[0],fixZero(aTmp[1]),aTmp[2]]).join('-') <= sDate2){
m++;
} else {
break;
}
}
//計算天數
aTmp = [aDate1[0]+y,aDate1[1]+m,aDate1[2]];
if(aTmp[1] > 12){
aTmp[0]++;
aTmp[1] -= 12;
}
while(true){
if(aTmp[2] == getMonthDays(aTmp[0],aTmp[1])){
aTmp[1]++;
aTmp[2] = 1;
} else {
aTmp[2]++;
}
sTmp = ([aTmp[0],fixZero(aTmp[1]),fixZero(aTmp[2])]).join('-');
if(sTmp <= sDate2){
d++;
} else {
break;
}
}
return {y:y,m:m,d:d};
};
//獲取兩個日期之間的所有月份(包括區間)
function getMonthBetween(start, end) {//傳入的格式YYYY-MM
var result = [];
var s = start.split("-");
var e = end.split("-");
var min = new Date();
var max = new Date();
min.setFullYear(s[0], s[1] * 1 - 1, 1);//開始日期
max.setFullYear(e[0], e[1] * 1 - 1, 1);//結束日期
var curr = min;
while (curr <= max) {
/**
* 單返回月份
*/
// var month = curr.getMonth();
// result.push(month + 1);
// curr.setMonth(month + 1);
/**
* 返回區間
*/
var month = curr.getMonth();
var str = curr.getFullYear()+'-'+(month+1);
var s = curr.getFullYear()+'-0';
if(str==s){
str = curr.getFullYear()+'-1';
}
//返回區間
result.push(str);
curr.setMonth(month + 1);
};
let arr = [];
result.forEach(v=>{
const day = utility.getLastDay(v);
arr.push(v.replace('-','年')+'月1日'+'-'+v.replace('-','年')+'月'+day+'日');
})
return arr;
// return result;//返回月份
};
//獲取指定月份的最後一天
function getLastDay(date){
let nowyear = new Date(date).getFullYear();//取當前的年份
let nowmonth = new Date(date).getMonth()+1;//獲取當前月份
let nextmonth = nowmonth++;//取下一個月的第一天,方便計算(最後一天不固定)
if(nowmonth>12){
nextmonth -= 12;//月份減
nowyear++;//年份增
};
var new_date = new Date(nowyear,nextmonth,1);//取當年當月中的第一天
return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//獲取當月最後一天日期
};
/**
* 將數字轉化爲大寫金額
*/
function changeNumMoneyToChinese(money){
var cnNums = new Array("零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"); //漢字的數字
var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本單位
var cnIntUnits = new Array("", "萬", "億", "兆"); //對應整數部分擴展單位
var cnDecUnits = new Array("角", "分", "毫", "釐"); //對應小數部分單位
var cnInteger = "整"; //整數金額時後面跟的字符
var cnIntLast = "元"; //整型完以後的單位
var maxNum = 999999999999999.9999; //最大處理的數字
var IntegerNum; //金額整數部分
var DecimalNum; //金額小數部分
var ChineseStr = ""; //輸出的中文金額字符串
var parts; //分離金額後用的數組,預定義
var Symbol="";//正負值標記
if (money == "") {
return "";
}
money = parseFloat(money);
if (money >= maxNum) {
alert('超出最大處理數字');
return "";
}
if (money == 0) {
ChineseStr = cnNums[0] + cnIntLast + cnInteger;
return ChineseStr;
}
if(money<0)
{
money=-money;
Symbol="負 ";
}
money = money.toString(); //轉換爲字符串
if (money.indexOf(".") == -1) {
IntegerNum = money;
DecimalNum = '';
} else {
parts = money.split(".");
IntegerNum = parts[0];
DecimalNum = parts[1].substr(0, 4);
}
if (parseInt(IntegerNum, 10) > 0) { //獲取整型部分轉換
var zeroCount = 0;
var IntLen = IntegerNum.length;
for (var i = 0; i < IntLen; i++) {
var n = IntegerNum.substr(i, 1);
var p = IntLen - i - 1;
var q = p / 4;
var m = p % 4;
if (n == "0") {
zeroCount++;
}
else {
if (zeroCount > 0) {
ChineseStr += cnNums[0];
}
zeroCount = 0; //歸零
ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
}
if (m == 0 && zeroCount < 4) {
ChineseStr += cnIntUnits[q];
}
}
ChineseStr += cnIntLast;
//整型部分處理完畢
}
if (DecimalNum != '') { //小數部分
var decLen = DecimalNum.length;
for (var i = 0; i < decLen; i++) {
var n = DecimalNum.substr(i, 1);
if (n != '0') {
ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
}
}
}
if (ChineseStr == '') {
ChineseStr += cnNums[0] + cnIntLast + cnInteger;
} else if (DecimalNum == '') {
ChineseStr += cnInteger;
}
ChineseStr = Symbol +ChineseStr;
return ChineseStr;
};
編寫自己的js工具庫
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.