实用代码片段

1、给所有的元素添加outline(不影响布局):

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

2、获取元素的样式:

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

3、比typeof运算符更准确的类型判断函数

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();
}

4、在上面这个type函数的基础上,还可以加上专门判断某种类型数据的方法(Firefox 和Chrome 的Array 类型都有forEach的函数):

['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:

(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);})()

 各种浏览器版本判断:

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
      }
    }
  })
}

 

 

 角度弧度转换:

角度转弧度 π/180×角度
弧度变角度 180/π×弧度

 背景音乐播放:

/////////
    //背景音乐 //
    /////////
    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:

(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);

 自定义事件封装:

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();  
}

 

posted @ 2016-05-31 10:46  黑客PK  阅读(671)  评论(0编辑  收藏  举报