JavaScript前端实用小函数

226 阅读1分钟

参考:火辣辣前端博客

1、判断是手机还是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;
}

2、判断手机是横屏还是竖屏

var isPortrait = true; //竪屏
function onMatchMeidaChange() {
	var mql = window.matchMedia('(orientation: portrait)')
	if(mql.matches) {
		// 竖屏
		isPortrait = true;
	} else {
		//橫屏
		isPortrait = false;
	}
}
onMatchMeidaChange();
window.matchMedia('(orientation: portrait)').addListener(onMatchMeidaChange);

3、简单的防抖动函数

function debounce(func, wait, immediate) {
	// 定时器变量
	var timeout;
	return function() {
		// 每次触发 scroll handler 时先清除定时器
		clearTimeout(timeout);
		// 指定 xx ms 后触发真正想进行的操作 handler
		timeout = setTimeout(func, wait);
	};
};  
// 采用了防抖动
var i=0;
window.addEventListener('scroll',debounce(function(){ 
   //功能代码 
   console.log(i);
},500));

4、简单的节流函数

// 简单的节流函数
function throttle(func, wait, mustRun) {
    var timeout,
        startTime = new Date(); 
    return function() { 
       var context = this, 
           args = arguments,
            curTime = new Date();
         clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔,触发 handler
        if(curTime - startTime >= mustRun){
            func.apply(context,args);
            startTime = curTime;
        // 没达到触发间隔,重新设定定时器 
       }else{
            timeout = setTimeout(func, wait);
        }
    };
};
  // 采用了节流函数
var i=0;
window.addEventListener('scroll',throttle(function(){ 
   //功能代码
    console.log(i);
},500,1000));

5、判断是手机QQ内置浏览器还是外部浏览器

function isQQ(){
	var ua = navigator.userAgent.toLowerCase();
	if (ua.match(/QQ/i) == "qq") { 
           return true; 
   	}
}

6、判断是不是微信端

function isWeChat() {
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('MicroMessenger') > -1) {
		return true;
  	}
}

7、判断ie浏览器版本

function IEVersion() {
			var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  			var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
  			if(isIE) {
				var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
				reIE.test(userAgent);
				var fIEVersion = parseFloat(RegExp["$1"]);
				if(fIEVersion >= 9) {
					console.log("浏览器版本为IE9以上版本");
				} else {
					console.log("浏览器版本为IE8以下版本");
				}
			}
		}

8、 浏览器刷新回到顶部

window.onbeforeunload = function() {
			document.documentElement.scrollTop = 0; //ie下
			document.body.scrollTop = 0; //非ie
}