收集一些經常使用方法,思之補之踩過的坑;css
斷定瀏覽器是否爲移動端,而後to do something:android
$(function isMobileBrowser() { var sUserAgent = navigator.userAgent.toLowerCase(); var bIsIpad = sUserAgent.match(/ipad/i) == "ipad"; var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os"; var bIsMidp = sUserAgent.match(/midp/i) == "midp"; var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"; var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb"; var bIsAndroid = sUserAgent.match(/android/i) == "android"; var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce"; var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile"; if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM ){ return true; }else return false; })()
曾經的錯誤…,js能夠獲取上一個訪問的頁面,可用於多個場景,而且刷新頁面此值不變:web
document.referrer
js中計算一些帶小數的數字會得出小數點很是長的現象例如2.01-1.02=0.9899999999999998,由於js中是將數字轉成二進制進行計算而後再轉成數字:windows
var ComputAmount = function(arg1, arg2, computType) { var r1, r2, m; try { r1 = arg1.toString().split(".")[1].length } catch(e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length } catch(e) { r2 = 0 } m = Math.pow(10, Math.max(r1, r2)) if(computType == 1) { return((arg1 * m + arg2 * m) / m).toFixed(2); } else { return((arg1 * m - arg2 * m) / m).toFixed(2); } }
三個參數,第一個數字,第二個數字,第三個是加減的參數,改動能夠用於乘除;瀏覽器
判斷url是否存在某search參數,稍改動可獲取某search參數的值:cookie
function giveQuery(p) { var httppath = "www.baidu.com?a=b&c=d", httppath = httppath.substring(13); //?a=b&c=d 此處可優化 //var httppath=location.search; //?a=b&c=d search = httppath.length > 0 ? httppath.substring(1) : "", //a=b&c=d items = search.length > 0 ? search.split("&") : [], //["a=b", "c=d"] item = null, t = false, len = items.length; //2 for(i = 0; i < len; i++) { item = items[i].split("="); if(item[0] == p) { console.log(item[1]); t = true; } } if(!t) { console.log("search is null") } }
讀取Cookie值:app
var getCookie = function(name) { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if(arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; };
瀏覽器居中顯示提示消息,移動端應用的多些:iphone
var alertMsg = function(text) { //拼接div 或者display div //class=alertBg 設置透明蒙版等 $("body").append('<div class="alertBg" id="alertMsg">' + text + '</div>'); var $height = $("#alertMsg").outerHeight() / 2, $width = $("#alertMsg").outerWidth() / 2; $("#alertMsg").css({ marginLeft: -$width, marginTop: -$height }); $("#alertMsg").show().fadeOut(3000, function() { $(this).remove(); }); }
舊版瀏覽器(IE678)提示:優化
var isIE7older = document.all && !document.querySelector, isIE8older = document.all && document.querySelector && !document.addEventListener; if(isIE7older || isIE8older) { doSomeThing() }
原版 2017-03-07發佈於xuechenlei.comthis