經常使用的功能封裝 pool.js

//import { setInterval } from "timers";

//獲取最大值
function getMax(){
    var max = arguments[0];
    for(var i=0;i<arguments.length;i++){
        if(max<=arguments[i]){
            max=arguments[i]
        }
    }
    return max;
}
//
//獲取最小值
function getMin(){
    var min =arguments[0];
    for(var i=0;i<arguments.length;i++){
        if(min>=arguments[i]){
            min=arguments[i]
        }
    }
    return min;
}

//隨機數 n小於m
function random1Num(n,m){
    return parseInt(n+Math.random()*(m-n+1));
}

//打亂隨機排序

function random1Number(arr){
    arr.sort(function(){
        return 0.5-Math.random();
    })

    return arr;
}

//返回最大值   傳入的參數是數組
function getMax(arr){
    var max = arr[0];
    for(var i=0;i<arr.length;i++){
        if(max<arr[i]){
            max=arr[i]
        }
    }
    return max;
}

//返回最小值   傳入的參數是數組
function getMin(arr){
    var min = arr[0];
    for(var i=0;i<arr.length;i++){
        if(min>arr[i]){
            min=arr[i]
        }
    }
    return min;
}

//返回最大值的下標  傳入的是數組
function getMaxIndex(arr){
    var max = arr[0];
    var index;
    for(var i=0;i<arr.length;i++){
        if(max<arr[i]){
            max=arr[i]
            index=i;
        }
    }
    return index;
}

//返回最小下標  傳入的是數組
function getMinIndex(arr){
    var min = arr[arr.length-1];
    var index=arr.length-1;
    for(var i=0;i<arr.length;i++){
        if(min>arr[i]){
            min=arr[i];
            index=i;
        }
    }
    return index;
}

//冒泡排序  傳入的是數組
function bubbling(arr){
    var temp;
    for(var i=0;i<arr.length-1;i++){
        for(var j=0;j<arr.length-1-i;j++){
            if(arr[j]>arr[j+1]){
                temp = arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;

            }
        }
    }
    return arr;
}

//選擇排序 傳入的是數組
function selectSort(arr){
    var temp;
    for(var i=0;i<arr.length-1;i++){
        for(var j=i+1;j<arr.length;j++){
            if(arr[i]>arr[j]){0
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
//數組判斷是否有某個值
//傳入的值是一個數組  n是一個字符
function has(arr,n){
    for(var i in arr){
        if(arr[i]===n){
            return true;
        }
    }
    return false;
}

//數組去重
function norepeat(arr){
    var newArr = [];
    for(var i in arr){
        if(!has(newArr,arr[i])){
            newArr.push(arr[i])
        }
    }
    return newArr;
}

//數組插入 按照原來順序排序
function sort1Arr(arr,n){            
    for(var i=0;i<arr.length;i++){
        if(arr[arr.length-1]<n){
        arr.push(n);
        }else if(arr[i]>n){
        arr.splice(i,0,n);
        break;
        }
        }
    return arr    
}
//驗證碼  6位數的驗證碼
function authCode(){
    var str = '';
    while(str.length<6){
        var num = random1Num(48,122)
    
        if((num>57&&num<65)||(num>90&&num<97)){
            num = random1Num(48,122)
        }else{
            str+=''+String.fromCharCode(num)
        }
        
    }
    return str
}

//隨機顏色
function randomColor(){
    var R = random1Num(0,255)
    var G = random1Num(0,255)
    var B = random1Num(0,255)
    return "#"+string2Num(R,G,B) 
}
//轉換爲16進制不足補0
function string2Num(r,g,b){
    r = r.toString(16).length<2?"0"+r.toString(16):r.toString(16);
    g = g.toString(16).length<2?"0"+g.toString(16):g.toString(16);
    b = b.toString(16).length<2?"0"+b.toString(16):b.toString(16);
    return r+g+b;
}
//當前時間
function getdate(sign){
    var date = new Date();
    var time = (date.getFullYear()+"") +sign+ ((String(date.getMonth()+1)).length<2?("0"+String(date.getMonth()+1)):(String(date.getMonth()+1))) +sign+ ((String(date.getDate())).length<2?("0"+String(date.getDate())):(String(date.getDate())))
    return time;
}

//將時間對象轉換成字符串
function date2String(d,sign){
    if(sign==undefined){
        sign="/"
    }

    return d.getFullYear()+sign+addzero((d.getMonth()+1))+sign+addzero(d.getDate())+" "+addzero(d.getHours())+":"+addzero(d.getMinutes())+":"+addzero(d.getSeconds());
}
//當數字不足兩位的時候補0  應用於時間對象
function addzero(num){
    var str = ""+num;
    return str.length<2?"0"+str:str;
}
//獲取id元素
function $(id){
    var id = id.slice(1,id.length)
   return document.getElementById(id)
}
//獲取非行間樣式
//ele:對象
//attr:屬性
function getStyle(ele,attr){
    if(ele.currentStyle){
        return ele.currentStyle[attr];
    }else{
        return getComputedStyle(ele,false)[attr]
    }
}
//隱藏
function hide(ele){
    ele.style.display="none";
}
//顯示
function show(ele){
    ele.style.display="block";
}
//獲取設置自定義屬性
function attr(ele,type,val){
    if(arguments.length<2){return};

    if(arguments.length==2){
        return ele.getAttribute(type);
    }

    ele.setAttribute(type,val);
}
//獲取到前一個兄弟節點(元素)
function prevChild(ele) {
     return ele.previousElementSibling;
}
//獲取當前元素距離頁面的距離
function offset(ele){
    var obj = {};
    obj.l = ele.offsetLeft;
    obj.t = ele.offsetTop;

    while(ele.offsetParent){
        var ele = ele.offsetParent;
        obj.l+=ele.offsetLeft;
        obj.t+=ele.offsetTop;
    }
    return obj;
}

//阻止瀏覽器默認行爲
function prevent(e){
    e.preventDefault?e.preventDefault():e.returnValue = false;
}

//事件監聽
//第一次參數:對象
//第二個參數:事件類型
//第三個參數:回調函數
//第四個參數:是否捕獲
function attach(ele,type,fn,bool){
    if(!bool){
        bool=false;
    }
    if(ele.addEventListener){
        ele.addEventListener(type,fn,bool)
    }else{
        ele.attachEvent("on"+type,fn)
    }
}

//阻止事件冒泡
function cancel(e){
    e.stopPropagetion?e.stopPropagetion():e.cancelBubble = true;
}

//判斷是不是閏年
function leap(year){
    return (year%4==0)&&(year%100!=0||year%400==0)
}

//設置cookie
function setCookie(_name,_val,expires){
    var d = new Date();
    d.setDate(d.getDate()+expires);
    document.cookie = _name+"="+_val+";expires="+d;
}

//獲取cookie
function getCookie(_name){
    var cookie = document.cookie;
    var arr = cookie.split("; ")
    for(var i=0;i<arr.length;i++){
        var newArr = arr[i].split("=");
        if(newArr[0]==_name){
            return newArr[1];
        }
    }
}

//刪除cookie
function removeCookie(_name,_val){
    setCookie(_name,_val,-1)
}
//獲取className 無兼容性問題  
//父級元素
//class類名
function getClassName(parent,aClass){
    //獲取到父元素底下全部的子元素
    var aEle = parent.getElementsByTagName('*');
    var arr = [];
    //匹配傳進來的這個字符是否是一個邊界符
    var reg = new RegExp('\\b'+aClass+'\\b');
    for(var i=0;i<aEle.length;i++){
        if(reg.test(aEle[i].className)){
            arr.push(aEle[i])
        }
    }
    return arr;
}

//運動框架
function move(obj,json,fn){
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
        var bStop = true;
        for(var attr in json){
            var iCur = 0;
            if(attr=='opacity'){
                iCur = parseInt(parseFloat(getStyle(obj,attr))*100)
            }else{
                iCur = parseInt(getStyle(obj,attr))
            }

            if(iCur!=json[attr]){
                bStop=false;
            }


            var speed = (json[attr]-iCur)/8;
            speed = speed>0?Math.ceil(speed):Math.floor(speed);

            
            if(attr=='opacity'){
                obj.style.opacity = (iCur+speed)/100;
                obj.style.filter = 'alpha(opacity:'+(iCur+speed)+')'
            }else{
                obj.style[attr]=iCur+speed+'px';
            }
        }

        if(bStop){
            clearInterval(obj.timer);
            if(fn){
                fn();
            }
        }
    },30)
}
//獲取url參數
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象
    var r = window.location.search.substr(1).match(reg); //匹配目標參數
    if (r != null) return unescape(r[2]); return null; //返回參數值
   }
//初始化倒計時
function counttime(){
    const timeCount = 60;
    this.count = timeCount;
    this.timer = setInterval(function(){
        if(this.count > 0 && this.count <=timeCount){
            this.count--
        } else {
            clearInterval(this.timer)
            this.timer = null
        }
    },1000)
}
//適應移動端的viewport自適應
//<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> 
//<meta name="format-detection" content="telephone=no">
//uc強制豎屏
//<meta name="screen-orientation" content="portrait">
//qq強制豎屏
//<meta name="x5-orientation" content="portrait">
//uc強制全屏
//<meta name="full-screen" content="yes">
//qq強制全屏
//<meta name="x5-fullscreen" content="true">
//uc應用模式
//<meta name="browsermode" content="application">
//qq應用模式
//<meta name="x5-page-mode" content="app">
//金額千分位分割
function fenge(str){
    return Number(str).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g,"$1,")
    
}
//獲取前一週的日期
var date = new Date();
date.setDate(date.getDate()-7);
var oneweekdate = date.getFullYear() + "-" + addzero(date.getMonth()+1) + "-" + addzero(date.getDate())

//移動端添加固定的額高度
function scrollH(rem){
    var el = document.getElementById("app");
    var doc = document.documentElement;
    el.style.height = (parseFloat(doc.clientHeight)) - (parseFloat(doc.style.fontSize)*parseFloat(rem)) + "px"
}
//永久本地存儲
function save(key,value){
    localStorage.setItem(key,JSON.stringify(value))
}
//獲取永久本地存儲
function fecth(key){
    return JSON.parse(localStorage.getItem(value))
}
//ios自動聚焦
document.addEventListener('touchstart',function(e){
    document.getElementById("ipt").focus();
})
//監聽歷史記錄
pushHistory();
window.addEventListener("popstate",function(e){
window.location = "http://baibu.com";

},false);
function pushHistory(){
var state = {
    title:'baidu',
    url:""
};
window.history.pushState(state,"title","");
}
//jq插件
jQuery.fn.extend({
    text:function(value){
        return access(this,function(value){
            return value ===undefined?
            jQuery.text(this):
            this.empty().each(function(){
                if(this.nodeType === 1 || this.nodeType ===11 || this.nodeType===9){
                    this.textContent = value;
                }
            })
        })
    }
})
//金額千分位分割
function fenge(str){
    str = Number(str).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g,"$1,");
    return str;
}
//金額輸入正則表達式
function formNum(obj){
    obj.value = obj.value.replace(/[^0-9.]+/,"");//清除number和’.‘之外的字符
    obj.value = obj.value.replace(/^\./g,"");//第一個字符是數字
    obj.value = obj.value.replace(/\.{2,}/g,"");//只保留第一個'.',清除多餘的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");//
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,"$1$2.$3")//只能輸入兩位小數
}
//判斷是不是閏年
function pyear(year){
    return (year%4 == 0) || (year%100!=0 && year%400==0)
}
//判斷月份的天數
function mdays(year,mouth){
    var days = 0;
    if(mouth==1||mouth==3||mouth==5||mouth==7||mouth==8||mouth==10||mouth==12){
        days=31;
    }else if(mouth==6||mouth==4||mouth==9||mouth==11){
        days=30;
    }else if(mouth==2 && ((year%4 == 0) || (year%100!=0 && year%400==0))){
        days=29;
    }else if(mouth==2){
        days=28;
    }
    return days;
}
//日期20180808=>2018-08-08
//vue filter.js
//export const formateDate = Vue.filter('formateDate',function(val){
//     var year = val.substr(0,4)
//     var month = val.substr(4,2)
//     var day = val.substr(-2)
//     return year + "-" + month + "-" +day
// })

//卡號四位加一空格
//export const formateaccoutNo = Vue.filter('formateaccoutNo',function(val){
//     var accoutNo = '';
//     for(var i=0;i<5;i++){
//         accountNo = accoutNo + val.substr(i*4,4) + ''
//     }
//     return accoutNo
// })

//金額轉成大寫
function converChinese(money){
    //漢字的數字
    var cnNums = new Array('零','壹','貳','叄','肆','伍','陸','柒','捌','玖');
    //基本單位
    var cnIntRadice = new Array('','拾','佰','仟');
    //對應整數部分擴展單位
    var cnIntUnits = new Array('','萬','億','兆');
    //對應小數部分單位
    var cnDecUnits = new Array('角','分','毫','釐');
    //整數金額時後面跟的單位
    var cnInteger = "整";
    //整型後的單位
    var cnIntLast = '元';
    //最大處理的數字
    var maxNum = 9999999999999999.9999;
    //金額整數部分
    var integerNum;
    //金額小數部分
    var decimalNum;
    //輸出的中文金額字符串
    var chineseStr = '';
    //分離金額後用的數組,預約義
    var parts;
    if(money == ''){
        return '';
    }
    money = parseFloat(money)
    //超出最大處理數字
    if(money >= maxNum){
        return ''
    }
    if(money == 0){
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
    }
    //轉換成字符串
    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;
    }
    return chineseStr;
}


//初始化短信倒計時
function getCodel(){
    const timeCount = 60;
    var count = timeCount;
    var self = this;
    this.timer = setInterval(function(){
        if(self.count > 0 && self.count <= timeCount){
            self.count --;
        } else {
            self.show = true;
            clearInterval(self.timer)
            self.timer = null
        }
    },1000)

}
//首字母大寫過濾器
// filters: {
//     capitalize: function (value) {
//       if (!value) return ''
//       value = value.toString()
//       return value.charAt(0).toUpperCase() + value.slice(1)
//     }
//ie9 placeholder模擬
function ifie9(){
    //判斷是不是ie9
    if(navigator.userAgent.indexOf("MSIE 9.0")>0){
        //input元素
        $(".ipt").each(function(){
            var self = $(this);
            self.parent().append('<span class="placeholder" data-type = "placeholder"></span>')
            if(self.val() != ''){
                self.parent().find("span.placeholder").hide()
            }else{
                self.parent().find("span.placeholder").show()
            }
        }).on('foucs',function(){
            $(this).parent().find("span.placeholder").hide()
        }).on('blur',function(){
            var self = $(this);
            if(self.val != ''){
                self.parent().find("span.placeholder").hide()
            }else{
                self.parent().find("span.placeholder").show()
            }
        });
        $("span.placeholder").on('clock',function(){
            $(this).hide()
        })
    }
}
//滾動條
$(document).ready(function() {
    $(window).scroll(function() {
        //$(document).scrollTop() 獲取垂直滾動的距離
        //$(document).scrollLeft() 這是獲取水平滾動條的距離
        if ($(document).scrollTop() <= 0) {
            alert("滾動條已經到達頂部爲0");
        }


        if ($(document).scrollTop() >= $(document).height() - $(window).height()) {
            alert("滾動條已經到達底部爲" + $(document).scrollTop());
        }
    });
});

//有就刪除,沒有就添加
$(".bo").toggleClass('box')

//保留兩位小數,非四捨五入

function cuntnum(num){
    if(num.toString().indexOf(".") > -1){
        var c = num.toString().indexOf(".")
        var d = num.toString().substr(c+1,2)
        var e = num.toString().substring(0,c+1)
        return e+d
    }else if(num.toString().indexOf(".") == -1){
        return num
    }
}

 

//import { setInterval } from "timers";

//獲取最大值
function getMax(){
     var max = arguments[ 0];
     for( var i= 0; i< arguments. length; i++){
         if( max<= arguments[ i]){
             max= arguments[ i]
        }
    }
     return max;
}
//
//獲取最小值
function getMin(){
     var min = arguments[ 0];
     for( var i= 0; i< arguments. length; i++){
         if( min>= arguments[ i]){
             min= arguments[ i]
        }
    }
     return min;
}

//隨機數 n小於m
function random1Num( n, m){
     return parseInt( n+ Math. random()*( m- n+ 1));
}

//打亂隨機排序

function random1Number( arr){
     arr. sort( function(){
         return 0.5- Math. random();
    })

     return arr;
}

//返回最大值 傳入的參數是數組
function getMax( arr){
     var max = arr[ 0];
     for( var i= 0; i< arr. length; i++){
         if( max< arr[ i]){
             max= arr[ i]
        }
    }
     return max;
}

//返回最小值 傳入的參數是數組
function getMin( arr){
     var min = arr[ 0];
     for( var i= 0; i< arr. length; i++){
         if( min> arr[ i]){
             min= arr[ i]
        }
    }
     return min;
}

//返回最大值的下標 傳入的是數組
function getMaxIndex( arr){
     var max = arr[ 0];
     var index;
     for( var i= 0; i< arr. length; i++){
         if( max< arr[ i]){
             max= arr[ i]
             index= i;
        }
    }
     return index;
}

//返回最小下標 傳入的是數組
function getMinIndex( arr){
     var min = arr[ arr. length- 1];
     var index= arr. length- 1;
     for( var i= 0; i< arr. length; i++){
         if( min> arr[ i]){
             min= arr[ i];
             index= i;
        }
    }
     return index;
}

//冒泡排序 傳入的是數組
function bubbling( arr){
     var temp;
     for( var i= 0; i< arr. length- 1; i++){
         for( var j= 0; j< arr. length- 1- i; j++){
             if( arr[ j]> arr[ j+ 1]){
                 temp = arr[ j];
                 arr[ j]= arr[ j+ 1];
                 arr[ j+ 1]= temp;

            }
        }
    }
     return arr;
}

//選擇排序 傳入的是數組
function selectSort( arr){
     var temp;
     for( var i= 0; i< arr. length- 1; i++){
         for( var j= i+ 1; j< arr. length; j++){
             if( arr[ i]> arr[ j]){ 0
                 temp = arr[ i];
                 arr[ i] = arr[ j];
                 arr[ j] = temp;
            }
        }
    }
     return arr;
}
//數組判斷是否有某個值
//傳入的值是一個數組 n是一個字符
function has( arr, n){
     for( var i in arr){
         if( arr[ i]=== n){
             return true;
        }
    }
     return false;
}

//數組去重
function norepeat( arr){
     var newArr = [];
     for( var i in arr){
         if(! has( newArr, arr[ i])){
             newArr. push( arr[ i])
        }
    }
     return newArr;
}

//數組插入 按照原來順序排序
function sort1Arr( arr, n){           
     for( var i= 0; i< arr. length; i++){
         if( arr[ arr. length- 1]< n){
         arr. push( n);
        } else if( arr[ i]> n){
         arr. splice( i, 0, n);
         break;
        }
        }
     return arr  
}
//驗證碼 6位數的驗證碼
function authCode(){
     var str = '';
     while( str. length< 6){
         var num = random1Num( 48, 122)
    
         if(( num> 57&& num< 65)||( num> 90&& num< 97)){
             num = random1Num( 48, 122)
        } else{
             str+= ''+ String. fromCharCode( num)
        }
        
    }
     return str
}

//隨機顏色
function randomColor(){
     var R = random1Num( 0, 255)
     var G = random1Num( 0, 255)
     var B = random1Num( 0, 255)
     return "#"+ string2Num( R, G, B)
}
//轉換爲16進制不足補0
function string2Num( r, g, b){
     r = r. toString( 16). length< 2? "0"+ r. toString( 16): r. toString( 16);
     g = g. toString( 16). length< 2? "0"+ g. toString( 16): g. toString( 16);
     b = b. toString( 16). length< 2? "0"+ b. toString( 16): b. toString( 16);
     return r+ g+ b;
}
//當前時間
function getdate( sign){
     var date = new Date();
     var time = ( date. getFullYear()+ "") + sign+ (( String( date. getMonth()+ 1)). length< 2?( "0"+ String( date. getMonth()+ 1)):( String( date. getMonth()+ 1))) + sign+ (( String( date. getDate())). length< 2?( "0"+ String( date. getDate())):( String( date. getDate())))
     return time;
}

//將時間對象轉換成字符串
function date2String( d, sign){
     if( sign== undefined){
         sign= "/"
    }

     return d. getFullYear()+ sign+ addzero(( d. getMonth()+ 1))+ sign+ addzero( d. getDate())+ " "+ addzero( d. getHours())+ ":"+ addzero( d. getMinutes())+ ":"+ addzero( d. getSeconds());
}
//當數字不足兩位的時候補0 應用於時間對象
function addzero( num){
     var str = ""+ num;
     return str. length< 2? "0"+ str: str;
}
//獲取id元素
function $( id){
     var id = id. slice( 1, id. length)
return document. getElementById( id)
}
//獲取非行間樣式
//ele:對象
//attr:屬性
function getStyle( ele, attr){
     if( ele. currentStyle){
         return ele. currentStyle[ attr];
    } else{
         return getComputedStyle( ele, false)[ attr]
    }
}
//隱藏
function hide( ele){
     ele. style. display= "none";
}
//顯示
function show( ele){
     ele. style. display= "block";
}
//獲取設置自定義屬性
function attr( ele, type, val){
     if( arguments. length< 2){ return};

     if( arguments. length== 2){
         return ele. getAttribute( type);
    }

     ele. setAttribute( type, val);
}
//獲取到前一個兄弟節點(元素)
function prevChild( ele) {
     return ele. previousElementSibling;
}
//獲取當前元素距離頁面的距離
function offset( ele){
     var obj = {};
     obj. l = ele. offsetLeft;
     obj. t = ele. offsetTop;

     while( ele. offsetParent){
         var ele = ele. offsetParent;
         obj. l+= ele. offsetLeft;
         obj. t+= ele. offsetTop;
    }
     return obj;
}

//阻止瀏覽器默認行爲
function prevent( e){
     e. preventDefault? e. preventDefault(): e. returnValue = false;
}

//事件監聽
//第一次參數:對象
//第二個參數:事件類型
//第三個參數:回調函數
//第四個參數:是否捕獲
function attach( ele, type, fn, bool){
     if(! bool){
         bool= false;
    }
     if( ele. addEventListener){
         ele. addEventListener( type, fn, bool)
    } else{
         ele. attachEvent( "on"+ type, fn)
    }
}

//阻止事件冒泡
function cancel( e){
     e. stopPropagetion? e. stopPropagetion(): e. cancelBubble = true;
}

//判斷是不是閏年
function leap( year){
     return ( year% 4== 0)&&( year% 100!= 0|| year% 400== 0)
}

//設置cookie
function setCookie( _name, _val, expires){
     var d = new Date();
     d. setDate( d. getDate()+ expires);
     document. cookie = _name+ "="+ _val+ ";expires="+ d;
}

//獲取cookie
function getCookie( _name){
     var cookie = document. cookie;
     var arr = cookie. split( "; ")
     for( var i= 0; i< arr. length; i++){
         var newArr = arr[ i]. split( "=");
         if( newArr[ 0]== _name){
             return newArr[ 1];
        }
    }
}

//刪除cookie
function removeCookie( _name, _val){
     setCookie( _name, _val,- 1)
}
//獲取className 無兼容性問題
//父級元素
//class類名
function getClassName( parent, aClass){
     //獲取到父元素底下全部的子元素
     var aEle = parent. getElementsByTagName( '*');
     var arr = [];
     //匹配傳進來的這個字符是否是一個邊界符
     var reg = new RegExp( ' \\ b'+ aClass+ ' \\ b');
     for( var i= 0; i< aEle. length; i++){
         if( reg. test( aEle[ i]. className)){
             arr. push( aEle[ i])
        }
    }
     return arr;
}

//運動框架
function move( obj, json, fn){
     clearInterval( obj. timer);
     obj. timer = setInterval( function(){
         var bStop = true;
         for( var attr in json){
             var iCur = 0;
             if( attr== 'opacity'){
                 iCur = parseInt( parseFloat( getStyle( obj, attr))* 100)
            } else{
                 iCur = parseInt( getStyle( obj, attr))
            }

             if( iCur!= json[ attr]){
                 bStop= false;
            }


             var speed = ( json[ attr]- iCur)/ 8;
             speed = speed> 0? Math. ceil( speed): Math. floor( speed);

            
             if( attr== 'opacity'){
                 obj. style. opacity = ( iCur+ speed)/ 100;
                 obj. style. filter = 'alpha(opacity:'+( iCur+ speed)+ ')'
            } else{
                 obj. style[ attr]= iCur+ speed+ 'px';
            }
        }

         if( bStop){
             clearInterval( obj. timer);
             if( fn){
                 fn();
            }
        }
    }, 30)
}
//獲取url參數
function getUrlParam( name) {
     var reg = new RegExp( "(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象
     var r = window. location. search. substr( 1). match( reg); //匹配目標參數
     if ( r != null) return unescape( r[ 2]); return null; //返回參數值
}
//初始化倒計時
function counttime(){
     const timeCount = 60;
     this. count = timeCount;
     this. timer = setInterval( function(){
         if( this. count > 0 && this. count <= timeCount){
             this. count--
        } else {
             clearInterval( this. timer)
             this. timer = null
        }
    }, 1000)
}
//適應移動端的viewport自適應
//<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
//<meta name="format-detection" content="telephone=no">
//uc強制豎屏
//<meta name="screen-orientation" content="portrait">
//qq強制豎屏
//<meta name="x5-orientation" content="portrait">
//uc強制全屏
//<meta name="full-screen" content="yes">
//qq強制全屏
//<meta name="x5-fullscreen" content="true">
//uc應用模式
//<meta name="browsermode" content="application">
//qq應用模式
//<meta name="x5-page-mode" content="app">
//金額千分位分割
function fenge( str){
     return Number( str). toFixed( 2). replace( / ( \d )(?=( \d {3} ) +\. ) / g, "$1,")
    
}
//獲取前一週的日期
var date = new Date();
date. setDate( date. getDate()- 7);
var oneweekdate = date. getFullYear() + "-" + addzero( date. getMonth()+ 1) + "-" + addzero( date. getDate())

//移動端添加固定的額高度
function scrollH( rem){
     var el = document. getElementById( "app");
     var doc = document. documentElement;
     el. style. height = ( parseFloat( doc. clientHeight)) - ( parseFloat( doc. style. fontSize)* parseFloat( rem)) + "px"
}
//永久本地存儲
function save( key, value){
     localStorage. setItem( key, JSON. stringify( value))
}
//獲取永久本地存儲
function fecth( key){
     return JSON. parse( localStorage. getItem( value))
}
//ios自動聚焦
document. addEventListener( 'touchstart', function( e){
     document. getElementById( "ipt"). focus();
})
//監聽歷史記錄
pushHistory();
window. addEventListener( "popstate", function( e){
window. location = "http://baibu.com";

}, false);
function pushHistory(){
var state = {
     title: 'baidu',
     url: ""
};
window. history. pushState( state, "title", "");
}
//jq插件
jQuery. fn. extend({
     text : function( value){
         return access( this, function( value){
             return value === undefined?
             jQuery. text( this):
             this. empty(). each( function(){
                 if( this. nodeType === 1 || this. nodeType === 11 || this. nodeType=== 9){
                     this. textContent = value;
                }
            })
        })
    }
})
//金額千分位分割
function fenge( str){
     str = Number( str). toFixed( 2). replace( / ( \d )(?=( \d {3} ) +\. ) / g, "$1,");
     return str;
}
//金額輸入正則表達式
function formNum( obj){
     obj. value = obj. value. replace( / [^ 0-9. ] + /, ""); //清除number和’.‘之外的字符
     obj. value = obj. value. replace( / ^ \. / g, ""); //第一個字符是數字
     obj. value = obj. value. replace( / \.{2,} / g, ""); //只保留第一個'.',清除多餘的
     obj. value = obj. value. replace( ".", "$#$"). replace( / \. / g, ""). replace( "$#$", "."); //
     obj. value = obj. value. replace( / ^ ( \- ) * ( \d + ) \. ( \d\d ) . * $ /, "$1$2.$3") //只能輸入兩位小數
}
//判斷是不是閏年
function pyear( year){
     return ( year% 4 == 0) || ( year% 100!= 0 && year% 400== 0)
}
//判斷月份的天數
function mdays( year, mouth){
     var days = 0;
     if( mouth== 1|| mouth== 3|| mouth== 5|| mouth== 7|| mouth== 8|| mouth== 10|| mouth== 12){
         days= 31;
    } else if( mouth== 6|| mouth== 4|| mouth== 9|| mouth== 11){
         days= 30;
    } else if( mouth== 2 && (( year% 4 == 0) || ( year% 100!= 0 && year% 400== 0))){
         days= 29;
    } else if( mouth== 2){
         days= 28;
    }
     return days;
}
//日期20180808=>2018-08-08
//vue filter.js
//export const formateDate = Vue.filter('formateDate',function(val){
//  var year = val.substr(0,4)
//  var month = val.substr(4,2)
//  var day = val.substr(-2)
//  return year + "-" + month + "-" +day
// })

//卡號四位加一空格
//export const formateaccoutNo = Vue.filter('formateaccoutNo',function(val){
//  var accoutNo = '';
//  for(var i=0;i<5;i++){
//      accountNo = accoutNo + val.substr(i*4,4) + ''
//  }
//  return accoutNo
// })

//金額轉成大寫
function converChinese( money){
     //漢字的數字
     var cnNums = new Array( '零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖');
     //基本單位
     var cnIntRadice = new Array( '', '拾', '佰', '仟');
     //對應整數部分擴展單位
     var cnIntUnits = new Array( '', '萬', '億', '兆');
     //對應小數部分單位
     var cnDecUnits = new Array( '角', '分', '毫', '釐');
     //整數金額時後面跟的單位
     var cnInteger = "整";
     //整型後的單位
     var cnIntLast = '元';
     //最大處理的數字
     var maxNum = 9999999999999999.9999;
     //金額整數部分
     var integerNum;
     //金額小數部分
     var decimalNum;
     //輸出的中文金額字符串
     var chineseStr = '';
     //分離金額後用的數組,預約義
     var parts;
     if( money == ''){
         return '';
    }
     money = parseFloat( money)
     //超出最大處理數字
     if( money >= maxNum){
         return ''
    }
     if( money == 0){
         chineseStr = cnNums[ 0] + cnIntLast + cnInteger;
         return chineseStr;
    }
     //轉換成字符串
     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;
    }
     return chineseStr;
}


//初始化短信倒計時
function getCodel(){
     const timeCount = 60;
     var count = timeCount;
     var self = this;
     this. timer = setInterval( function(){
         if( self. count > 0 && self. count <= timeCount){
             self. count --;
        } else {
             self. show = true;
             clearInterval( self. timer)
             self. timer = null
        }
    }, 1000)

}
//首字母大寫過濾器
// filters: {
// capitalize: function (value) {
// if (!value) return ''
// value = value.toString()
// return value.charAt(0).toUpperCase() + value.slice(1)
// }
//ie9 placeholder模擬
function ifie9(){
     //判斷是不是ie9
     if( navigator. userAgent. indexOf( "MSIE 9.0")> 0){
         //input元素
         $( ".ipt"). each( function(){
             var self = $( this);
             self. parent(). append( '<span class="placeholder" data-type = "placeholder"></span>')
             if( self. val() != ''){
                 self. parent(). find( "span.placeholder"). hide()
            } else{
                 self. parent(). find( "span.placeholder"). show()
            }
        }). on( 'foucs', function(){
             $( this). parent(). find( "span.placeholder"). hide()
        }). on( 'blur', function(){
             var self = $( this);
             if( self. val != ''){
                 self. parent(). find( "span.placeholder"). hide()
            } else{
                 self. parent(). find( "span.placeholder"). show()
            }
        });
         $( "span.placeholder"). on( 'clock', function(){
             $( this). hide()
        })
    }
}
//滾動條
$( document). ready( function() {
     $( window). scroll( function() {
         //$(document).scrollTop() 獲取垂直滾動的距離
         //$(document).scrollLeft() 這是獲取水平滾動條的距離
         if ( $( document). scrollTop() <= 0) {
             alert( "滾動條已經到達頂部爲0");
        }


         if ( $( document). scrollTop() >= $( document). height() - $( window). height()) {
             alert( "滾動條已經到達底部爲" + $( document). scrollTop());
        }
    });
});

//有就刪除,沒有就添加
$( ".bo"). toggleClass( 'box')

//保留兩位小數,非四捨五入改進版
function tofixedTwo(num){
    var bb = num+"";
    var dian = bb.indexOf('.');
    var result = "";
    if(dian == -1){
        result = num.toFixed(2);
    }else{
        var cc = bb.substr(dian+1,2);
        var dd = bb.substring(0,dian+1);
        if(cc.length < 2){
            result = dd + cc + "0";
        }else{
            result = dd + cc;
        }
    }
    return result
}
// encodeURI 加密和解密
var url = encodeURIComponent("https://www.baidu.com?a='王武傑'")
console.log(url,decodeURIComponent(url))
// 點擊除了特定元素以外的元素
function other(obj,othobj){//要點擊的元素和要去除的元素
    obj.click(function(event){
        var con = othobj
        if(!con.is(event.target) && con.has(event.target).length === 0){
            dosomething
        }
    })
}

if(!!document.all){
//ie瀏覽器處理,判斷是不是ie
}
//跨域請求頭設置
//後端設置請求頭部Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: www.xxx.com
//前端post請求設置withCredentials=true

//淘寶鏡像安裝node
//npm install -g cnpm –registry=https://registry.npm.taobao.org
//瀏覽器回退返回按鈕
var tempHash = window.location.hash;
if(window.history && window.history.pushState){
    window.addEventListener('popstate',function(){
        var hasLocation = location.hash;
        var hashSplit = hashLocation.split("#");
        var hashName = hashSplit[1];
        if(hashName != ''){
            var hash = window.location.hash;
            if(hash == tempHash){
                window.opener = null
                window.open("about:blank","_self","")
                window.close()
            }
        }
    });
    window.history.replaceState('forward',null,window.location.hash + '#forward');
    window.history.pushState('forward',null,tempHash);
    tempHash = window.location.hash;
}


window.history.forward(1);
//防止頁面後退
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
     history.pushState(null, null, document.URL);
});

//字符串動態建立dom
function parseDom(arg) {
       var objE = document.createElement("div");
       objE.innerHTML = arg;
       return objE.childNodes;
    };
    var obj=parseDom('<div id="div_1" class="div1">Hello World!</div>');
    //返回的obj是個數組
    console.log(obj[0])
    var box = document.getElementById("box")
    box.appendChild(obj[0])
相關文章
相關標籤/搜索