我们在开发中,经常会遇到相同的场景,需要用到相同的代码,所以这篇文章就总结一下。

去掉字符串首尾字符串

// 删除左右两端的空格
function trim(str){
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
// 删除左边的空格
function ltrim(str){
    return str.replace(/(^\s*)/g,"");
}
// 删除右边的空格
function rtrim(str){
    return str.replace(/(\s*$)/g,"");
}

捕获页面当前滚动位置

// 为保证兼容性,两者缺一不可
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

阻止冒泡

// JavaScript
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.event;
 
    if (event.stopPropagation){
        // W3C
        event.stopPropagation();
    } else{
        // IE
        event.cancelBubble = true;
    }
}, false);
 
// jQuery
$('#btn').on('click', function (event) {
    event.stopPropagation();
});

检测浏览器是否支持svg

function isSupportSVG() {
    var SVG_NS = 'http://www.w3.org/2000/svg';
    return !!document.createElementNS &&!!document.createElementNS(SVG_NS,'svg').createSVGRect;
}
 
console.log(isSupportSVG());

检测浏览器是否支持canvas

function isSupportCanvas() {
    if(document.createElement('canvas').getContext){
        return true;
    }else{
        return false;
    }
}
 
console.log(isSupportCanvas());

检测是否是微信浏览器

function isWeiXinClient() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}
 
alert(isWeiXinClient());

检测是否移动端及浏览器内核

var browser = {
    versions: function() {
        var u = navigator.userAgent;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Firefox') > -1, //火狐内核Gecko
            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
            iPhone: u.indexOf('iPhone') > -1 , //iPhone
            iPad: u.indexOf('iPad') > -1, //iPad
            webApp: u.indexOf('Safari') > -1 //Safari
        };
    }
}
 
if (browser.versions.mobile() || browser.versions.ios() || browser.versions.android() ||browser.versions.iPhone() || browser.versions.iPad()) {
    alert('移动端');
}

检测是否电脑端/移动端

var browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        var sUserAgent = navigator.userAgent;
        return {
        trident: u.indexOf('Trident') > -1,
        presto: u.indexOf('Presto') > -1,
        isChrome: u.indexOf("chrome") > -1,
        isSafari: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u),
        isSafari3: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u) && u.indexOf('webkit/5') != -1,
        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/),
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
        iPhone: u.indexOf('iPhone') > -1,
        iPad: u.indexOf('iPad') > -1,
        iWinPhone: u.indexOf('Windows Phone') > -1
        };
    }()
}
if(browser.versions.mobile || browser.versions.iWinPhone){
    window.location = "http:/www.baidu.com/m/";
}

检测浏览器内核

function getInternet(){    
    if(navigator.userAgent.indexOf("MSIE")>0) {    
      return "MSIE";       //IE浏览器  
    }  
 
    if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){    
      return "Firefox";     //Firefox浏览器  
    }  
 
    if(isSafari=navigator.userAgent.indexOf("Safari")>0) {    
      return "Safari";      //Safan浏览器  
    }  
 
    if(isCamino=navigator.userAgent.indexOf("Camino")>0){    
      return "Camino";   //Camino浏览器  
    }  
    if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){    
      return "Gecko";    //Gecko浏览器  
    }    
}

强制移动端页面横屏显示

$( window ).on( "orientationchange", function( event ) {
    if (event.orientation=='portrait') {
        $('body').css('transform', 'rotate(90deg)');
    } else {
        $('body').css('transform', 'rotate(0deg)');
    }
});
$( window ).orientationchange();

电脑端页面全屏显示

function fullscreen(element) {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}
 
fullscreen(document.documentElement);

获得/失去焦点

1、JavaScript实现

<input id="i_input" type="text" value="会员卡号/手机号"/>
// JavaScript
window.onload = function(){
    var oIpt = document.getElementById("i_input");
 
    if(oIpt.value == "会员卡号/手机号"){
        oIpt.style.color = "#888";
    }else{
        oIpt.style.color = "#000";
    };
 
    oIpt.onfocus = function(){
        if(this.value == "会员卡号/手机号"){
            this.value="";
            this.style.color = "#000";
            this.type = "password";
        }else{
            this.style.color = "#000";
        }
    };
    
    oIpt.onblur = function(){
        if(this.value == ""){
            this.value="会员卡号/手机号";
            this.style.color = "#888";
            this.type = "text";
        }
    };
}

2、jQuery实现

<input type="text" class="oldpsw" id="showPwd" value="请输入您的注册密码"/>
<input type="password" name="psw" class="oldpsw" id="password" value="" style="display:none;"/>
// jQuery
$("#showPwd").focus(function() {
    var text_value=$(this).val();
    if (text_value =='请输入您的注册密码') {
        $("#showPwd").hide();
        $("#password").show().focus();
    }
});
$("#password").blur(function() {
    var text_value = $(this).val();
    if (text_value == "") {
        $("#showPwd").show();
        $("#password").hide();
    }
});

获取上传文件大小

<input type="file" id="filePath" onchange="getFileSize(this)"/>
// 兼容IE9低版本
function getFileSize(obj){
    var filesize;
    
    if(obj.files){
        filesize = obj.files[0].size;
    }else{
        try{
            var path,fso;
            path = document.getElementById('filePath').value;
            fso = new ActiveXObject("Scripting.FileSystemObject");
            filesize = fso.GetFile(path).size;
        }
        catch(e){
            // 在IE9及低版本浏览器,如果不容许ActiveX控件与页面交互,点击了否,就无法获取size
            console.log(e.message); // Automation 服务器不能创建对象
            filesize = 'error'; // 无法获取
        }
    }
    return filesize;
}

限制上传文件类型

1、高版本浏览器

<input type="file" name="filePath" accept=".jpg,.jpeg,.doc,.docxs,.pdf"/>

2、限制图片

<input type="file" class="file" value="上传" accept="image/*">

3、低版本浏览器

<input type="file" id="filePath" onchange="limitTypes()">
/* 通过扩展名,检验文件格式。
* @parma filePath{string} 文件路径
* @parma acceptFormat{Array} 允许的文件类型
* @result 返回值{Boolen}:true or false
*/
 
function checkFormat(filePath,acceptFormat){
    var resultBool= false,
        ex = filePath.substring(filePath.lastIndexOf('.') + 1);
        ex = ex.toLowerCase();
        
    for(var i = 0; i < acceptFormat.length; i++){
      if(acceptFormat[i] == ex){
            resultBool = true;
            break;
      }
    }
    return resultBool;
};
        
function limitTypes(){
    var obj = document.getElementById('filePath');
    var path = obj.value;
    var result = checkFormat(path,['bmp','jpg','jpeg','png']);
    
    if(!result){
        alert('上传类型错误,请重新上传');
        obj.value = '';
    }
}

阻止默认行为

// JavaScript
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.event;
 
    if (event.preventDefault){
        // W3C
        event.preventDefault();
    } else{
        // IE
        event.returnValue = false;
    }
}, false);
 
// jQuery
$('#btn').on('click', function (event) {
    event.preventDefault();
});

禁止移动端浏览器页面滚动

HTML实现:

<body ontouchmove="event.preventDefault()">

JavaScript实现:

document.addEventListener('touchmove', function (e) {
    event.preventDefault();
});

图片懒加载

// 获取所有的内容图片
const imgList = $('img.child-page-img');

// 检查图片是否已经被显示
check();

// 滚动监听,如滚动则触发check函数
$('.main-content-right-wrap').on('scroll', check);

/**
 * 检查检查图片是否已经被显示
 */
function check() {
    // 选中imgList中没有展示的图片,然后判断未被展示的图片是否已经进入可视区域
    imgList.not('.show').each(function () {
        if (isShow($(this))) {
            showImg($(this));
        }
    });
}

/**
 * 判断元素是否进入可视区域
 * @Param node 元素节点
 */
function isShow(node) {
    const windowHeight = $(window).height();
    const scrollTop = $(window).scrollTop();
    const offsetTop = node.offset().top;
    const nodeHeight = node.height();
    return windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight;
}

/**
 * 展示图片
 * @Param imgs 图片节点数组
 */
function showImg(imgs) {
    imgs.each(function () {
        var imgUrl = $(this).attr('data-src');
        $(this).attr('src', imgUrl);
        $(this).addClass('show');
    })
}

回到页面顶部

// jQuery
$('.container')[0].scrollTop = 0;

// js
document.getElementsByClassName('container')[0].scrollTop = 0;

隐式转换

这是一个很有意思的转换,但是一般没什么卵用。

const obj = {
    valueOf: function() {
        return 42;
    },
    toString: function() {
        return 4;
    },
};

obj + '';   // 42,直接作为变量会执行valueOf方法。
String(obj);   // 4,用String类包裹会调用toString方法。

数据检查类型

普通类型检查可以使用typeof来检查,但是遇到对象、数组就无法明显的区分开,所以可以这样区分:

function isObject(value) {
    return Object.prototype.toString.call(value).slice(8, -1) === 'Object';
}

function isArray(value) {
    return Object.prototype.toString.call(value).slice(8, -1) === 'Array';
}

// 这种方法同样也适用于Function等
function isFunction(value) {
    return Object.prototype.toString.call(value).slice(8, -1) === 'Function';
}

多维数组变一维

这种情况经常出现在笔试题和面试题中。

const arr = [1, 2, ['3', 4], [5]];

arr.toString().split(',');   // 结果全部变为字符类型
JSON.parse(`[${JSON.stringify(foo).replace(/\[|]/g, '')}]`);   // 元素类型不变

动态插入js

function injectScript(src) {    
    var s, t;
    s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = src;
    t = document.getElementsByTagName('script')[0];
    t.parentNode.insertBefore(s, t);
}

大数字格式化

一般在表示大金额、大数据的时候,为了便于阅读,会进行格式化处理。

'2313123'.replace(/\B(?=(\d{3})+(?!\d))/g, ',');   // "2,313,123"

浮点数取整

浮点数取整,除了parseInt,还有别的方法:

const a = 12.34;
a | 0;   // 12
a >> 0;   // 12
~~a;   // 12
Math.floor(a);   // 13

const b = -12.34;
b | 0;   // -12
b >> 0;   // -12
~~b;   // -12
Math.floor(b);   // -13

生成验证码

js生成验证码可以使用Math.random函数:

Math.random().toString().slice(-6);

Math.random().toFixed(6).slice(-6);

'' + Math.floor(Math.random() * 999999);