實用代碼片斷

一、給全部的元素添加outline(不影響佈局):css

[].forEach.call(document.querySelectorAll("*"),function(a){a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)});

二、獲取元素的樣式:html

function getStyle(obj,attr){
     return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,null)[attr];
 }

三、比typeof運算符更準確的類型判斷函數jquery

var type = function (o){
    var s = Object.prototype.toString.call(o);
    return s.match(/\[object (.*)?\]/)[1].toLowerCase();
};

type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"

var isClass = function(o){
  if(o === null) {return null}
  if(o === undefined
) {return undefined}
  return Object.prototype.toString.call(o).slice(8,-1).toLowerCase();
}

四、在上面這個type函數的基礎上,還能夠加上專門判斷某種類型數據的方法(Firefox 和Chrome 的Array 類型都有forEach的函數):android

['Null',
 'Undefined',
 'Object',
 'Array',
 'String',
 'Number',
 'Boolean',
 'Function',
 'RegExp',
 'Element',
 'NaN',
 'Infinite'
].forEach(function (t) {
    type['is' + t] = function (o) {   //type沒有加var return type(o) === t.toLowerCase();
    };
});

type.isObject({}); // true
type.isNumber(NaN); // false
type.isElement(document.createElement('div')); // true
type.isRegExp(/abc/); // true

 顯示FPS:ios

(function(){var script=document.createElement('script');script.onload=function(){var stats=new Stats();document.body.appendChild(stats.dom);requestAnimationFrame(function loop(){stats.update();requestAnimationFrame(loop)});};script.src='//rawgit.com/mrdoob/stats.js/master/build/stats.min.js';document.head.appendChild(script);})()

 各類瀏覽器版本判斷:css3

function parseUA() {
            var u = navigator.userAgent;
            var u2 = navigator.userAgent.toLowerCase();
            return { //移動終端瀏覽器版本信息
                trident: u.indexOf('Trident') > -1, //IE內核
                presto: u.indexOf('Presto') > -1, //opera內核
                webKit: u.indexOf('AppleWebKit') > -1, //蘋果、谷歌內核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐內核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否爲移動終端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios終端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android終端或uc瀏覽器
                iPhone: u.indexOf('iPhone') > -1, //是否爲iPhone或者QQHD瀏覽器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web應該程序,沒有頭部與底部
                iosv: u.substr(u.indexOf('iPhone OS') + 9, 3),
                weixin: u2.match(/MicroMessenger/i) == "micromessenger",
                ali: u.indexOf('AliApp') > -1,
            };
        }
        var ua = parseUA();

        if (!ua.mobile) {
            location.href = './pc.html';
        }

        if (ups.utm_source == 'Newspaper-Haixia' && ups.utm_medium == 'Qrcode' && ups.utm_campaign == 'TB_zaovideo') {
            location.href = 'http://zaovideo.im20.com.cn/?utm_source=Newspaper-Haixia&utm_medium=Qrcode&utm_campaign=TB_zaovideo';
        }


///////////第二種

const ua = navigator.userAgent

const isAndroid = /(Android);?[\s\/]+([\d.]+)?/.test(ua)
const isIpad = /(iPad).*OS\s([\d_]+)/.test(ua)
const isIpod = /(iPod)(.*OS\s([\d_]+))?/.test(ua)
const isIphone = !isIpad && /(iPhone\sOS)\s([\d_]+)/.test(ua)
const isWechat = /micromessenger/i.test(ua)

export default function (Vue) {
  Vue.mixin({
    created: function () {
      this.$device = {
        isAndroid,
        isIpad,
        isIpod,
        isIphone,
        isWechat
      }
    }
  })
}
 
 

 

 

 角度弧度轉換:git

角度轉弧度 π/180×角度
弧度變角度 180/π×弧度

 背景音樂播放:web

/////////
    //背景音樂 //
    /////////
    function Hmlt5Audio(url,loop) {
        var audio = new Audio(url);
        audio.autoplay = true;
        audio.loop = loop|| false; //是否循環
        audio.play();
        return {
            end: function(callback) {
                audio.addEventListener('ended', function() {
                    callback()
                }, false);
            }
        }
    }

/////////
    //背景音樂 //
    /////////
    var audio1 = Hmlt5Audio('music/happy.wav')
    audio1.end(function() {
        Hmlt5Audio('music/circulation.wav',true)
    })

牢固的封裝requestAnimationFrame:ajax

(function(window){
    /*兼容處理requestAnimationFrame*/
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0,length = vendors.length; x < length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }
if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = function(callback, element) {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
        var id = window.setTimeout(function() {
                callback(currTime + timeToCall);
            }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    }
if (!window.cancelAnimationFrame) {
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
    }    
})(window);

 自定義事件封裝:json

var EventTarget = function() {
            this._listener = {};
        };

        EventTarget.prototype = {
            constructor: EventTarget,
            addEvent: function(type, fn) {
                if (typeof type === "string" && typeof fn === "function") {
                    if (typeof this._listener[type] === "undefined") {
                        this._listener[type] = [fn];
                    } else {
                        this._listener[type].push(fn);
                    }
                }
                return this;
            },
            addEvents: function(obj) {
                obj = typeof obj === "object" ? obj : {};
                var type;
                for (type in obj) {
                    if (type && typeof obj[type] === "function") {
                        this.addEvent(type, obj[type]);
                    }
                }
                return this;
            },
            fireEvent: function(type) {
                if (type && this._listener[type]) {
                    var events = {
                        type: type,
                        target: this
                    };

                    for (var length = this._listener[type].length, start = 0; start < length; start += 1) {
                        this._listener[type][start].call(this, events);
                    }
                }
                return this;
            },
            fireEvents: function(array) {
                if (array instanceof Array) {
                    for (var i = 0, length = array.length; i < length; i += 1) {
                        this.fireEvent(array[i]);
                    }
                }
                return this;
            },
            removeEvent: function(type, key) {
                var listeners = this._listener[type];
                if (listeners instanceof Array) {
                    if (typeof key === "function") {
                        for (var i = 0, length = listeners.length; i < length; i += 1) {
                            if (listeners[i] === key) {
                                listeners.splice(i, 1);
                                break;
                            }
                        }
                    } else if (key instanceof Array) {
                        for (var lis = 0, lenkey = key.length; lis < lenkey; lis += 1) {
                            this.removeEvent(type, key[lenkey]);
                        }
                    } else {
                        delete this._listener[type];
                    }
                }
                return this;
            },
            removeEvents: function(params) {
                if (params instanceof Array) {
                    for (var i = 0, length = params.length; i < length; i += 1) {
                        this.removeEvent(params[i]);
                    }
                } else if (typeof params === "object") {
                    for (var type in params) {
                        this.removeEvent(type, params[type]);
                    }
                }
                return this;
            }
        }; 

判斷數組元素是否重複

var isRepeat = function(arr) {  //arr是否有重複元素
    var hash = {};
    for (var i in arr) {
        if (hash[arr[i]]) return true;
        hash[arr[i]] = true;
    }
    return false;
};

獲取瀏覽器url中的參數值

var getURLParam = function(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
};

所有替換replaceAll

var replaceAll = function(bigStr, str1, str2) {  //把bigStr中的全部str1替換爲str2
    var reg = new RegExp(str1, 'gm');
    return bigStr.replace(reg, str2);
}

返回頂部

$(window).scroll(function() {
    var a = $(window).scrollTop();
    if(a > 100) {
        $('.go-top').fadeIn();
    }else {
        $('.go-top').fadeOut();
    }
});
$(".go-top").click(function(){
    $("html,body").animate({scrollTop:"0px"},'600');
});

jquery ajax函數封裝:

var Ajax = function(url, type success, error) {
    $.ajax({
        url: url,
        type: type,
        dataType: 'json',
        timeout: 10000,
        success: function(d) {
            var data = d.data;
            success && success(data);
        },
        error: function(e) {
            error && error(e);
        }
    });
};
// 使用方法:
Ajax('/data.json', 'get', function(data) {
    console.log(data);
});

jsonp方式--有時候咱們爲了跨域,要使用jsonp的方法,我也封裝了一個函數:

function jsonp(config) {
    var options = config || {};   // 須要配置url, success, time, fail四個屬性
    var callbackName = ('jsonp_' + Math.random()).replace(".", "");
    var oHead = document.getElementsByTagName('head')[0];
    var oScript = document.createElement('script');
    oHead.appendChild(oScript);
    window[callbackName] = function(json) {  //建立jsonp回調函數
        oHead.removeChild(oScript);
        clearTimeout(oScript.timer);
        window[callbackName] = null;
        options.success && options.success(json);   //先刪除script標籤,實際上執行的是success函數
    };
    oScript.src = options.url + '?' + callbackName;    //發送請求
    if (options.time) {  //設置超時處理
        oScript.timer = setTimeout(function () {
            window[callbackName] = null;
            oHead.removeChild(oScript);
            options.fail && options.fail({ message: "超時" });
        }, options.time);
    }
};
// 使用方法:
jsonp({
    url: '/b.com/b.json',
    success: function(d){
        //數據處理
    },
    time: 5000,
    fail: function(){
        //錯誤處理
    }       
});

操做cookie

own.setCookie = function(cname, cvalue, exdays){
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = 'expires='+d.toUTCString();
    document.cookie = cname + '=' + cvalue + '; ' + expires;
};
own.getCookie = function(cname) {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for(var i=0; i< ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return '';
};

 漂亮的隨機碼:

Math.random().toString(16).substring(2); //14位
Math.random().toString(36).substring(2); //11位

 獲取a連接的屬性:

var parser = function(url) {
    var a = document.createElement('a');
    a.href = url;

    var search = function(search) {
        if (!search) return {};

        var ret = {};
        search = search.slice(1).split('&');
        for (var i = 0, arr; i < search.length; i++) {
            arr = search[i].split('=');
            ret[arr[0]] = arr[1];
        }
        return ret;
    };

    return {
        protocol: a.protocol,
        host: a.host,
        hostname: a.hostname,
        pathname: a.pathname,
        search: search(a.search),
        hash: a.hash
    }
};

var url = 'http://sub.example.com:8088/index/?data=run&person=cc#hash';
parser(url);

console.log()//
  1. hash:"#hash"
  2. host:"sub.example.com:8088"
  3. hostname:"sub.example.com"
  4. pathname:"/index/"
  5. protocol:"http:"
  6. search:Object
  7. __proto__:Object

 針對安卓瀏覽器沒有刷新功能,調試不方便。

function addReLoad() {
        var reload = document.createElement('div');
        reload.style.cssText = 'display: block;position: fixed;left: 10px;bottom: 10px;color: #fff;background-color: #04be02;line-height: 1;font-size: 14px;padding: 8px 16px;z-index: 10000;border-radius: 4px;box-shadow: 0 0 8px rgba(0,0,0,.4);'
        reload.textContent = 'ReLoad';
        document.body.appendChild(reload);
        reload.addEventListener('click', function() {
            var random = Math.random().toString(36).slice(2);
            var href = window.location.href;
            if(href.indexOf('?')) {
                window.location.href = href.split('?')[0] + '?' + random;
            } else {
                window.location.href = href + '?' + random;
            }
        }, false);
    }

    addReLoad();

 js中bind的實現:

Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(
              this instanceof fNOP && oThis ? this : oThis || window,
              aArgs.concat(Array.prototype.slice.call(arguments))
          );
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };

 移動端屏蔽長按出現菜單:

document.oncontextmenu=function(){ 
window.event.returnValue=false; 
} 

 獲取基本的地址(basepath):

function getBasePath() {
        var basePath = '',
            origin   = '',
            pathName = '';
        if (origin in location) {
            origin = location.origin;
        } else {
            origin = location.protocol + "//" + location.hostname + (location.port ? ':' + location.port : '');
        }
        pathName = location.pathname.split('/');
        pathName.pop();
        pathName.push('');
        pathName = pathName.join('/')
        basePath = origin + pathName;
        return basePath;
    }

 audio標籤播放次數限制:

function playTimes(elem, times) {
    var start = 0;
    elem.addEventListener("ended",function() {
        start++;
        start == times && elem.pause();
    });
}

 不少個音頻但只播放一個音頻:

$('audio').on('click', function(){
    $('audio').not(this).each(function(){
        this.pause();
    });
});

 給css3屬性添加前綴及判斷兼容與否。

function vendorPropName(name) {
    // jquery源碼寫法
    var style = document.body.style;
    var cssPrefixes = ["O", "Moz", "ms", "Webkit"];
    if (name in style) {
        return name;
    }

    // check for vendor prefixed names
    var capName = name.charAt(0).toUpperCase() + name.slice(1),
        origName = name,
        i = cssPrefixes.length;

    while (i--) {
        name = cssPrefixes[i] + capName;

        if (name in style) {
            return name;
        }
    }
}
vendorPropName('animation');
// 若是不支持animation的話,直接返回undefined,因此使用以前須要先檢測

 

function vendorPropName(name) {// jquery源碼寫法    
    var style = document.body.style;    
    var cssPrefixes = ["O", "Moz", "ms", "Webkit"];    
    if (name in style) {return name;}
    // check for vendor prefixed names    
  var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,     i = cssPrefixes.length; while (i--) {     name = cssPrefixes[i] + capName; if (name in style) {       return name;    }   }  
} vendorPropName(
'animation'); // 若是不支持animation的話,直接返回undefined,因此使用以前須要先檢測

 

給對象數組中根據屬性值進行排序;

var infoObj=[
            {
                name:"張三",
                sex:'female',
                age:30
            },
            {
                name:"李四",
                sex:'male',
                age:20
            },
            {
                name:"王五",
                sex:'female',
                age:40
            }
        ];
        // 指定排序的比較函數
    function compare(property){
         return function(obj1,obj2){
             var value1 = obj1[property];
             var value2 = obj2[property];
             return value1 - value2;     // 升序
         }
    }
    var sortObj = infoObj.sort(compare("age"));
    console.log(sortObj); // 

 手機端給input添加拍照和選擇相冊:

<div style="visibility: hidden;">
       <input type="file" id="applyImageFil" accept="image/*" />
</div>

兼容全部微信瀏覽器清除下拉滑動代碼:(主要解決新升級的ios11.3以後不兼容)

document.body.addEventListener('touchmove', function (e) {
  e.preventDefault(); //阻止默認的處理方式(阻止下拉滑動的效果)
}, {passive: false}); //passive 參數不能省略,用來兼容ios和android

 隱藏微信瀏覽器右上角按鈕

document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
    WeixinJSBridge.call('hideOptionMenu');    // 經過下面這個API隱藏右上角按鈕
});
必須使用微信內置瀏覽器訪問本頁面
var useragent = navigator.userAgent;  
if (useragent.match(/MicroMessenger/i) != 'MicroMessenger') {  
    //alert('已禁止本次訪問:您必須使用微信內置瀏覽器訪問本頁面!');  
    var opened = window.open('about:blank', '_self');  
    opened.opener = null;  
    opened.close();  
}
相關文章
相關標籤/搜索