html{font-size:10px} @media screen and (min-width:321px) and (max-width:375px){html{font-size:11px}} @media screen and (min-width:376px) and (max-width:414px){html{font-size:12px}} @media screen and (min-width:415px) and (max-width:639px){html{font-size:15px}} @media screen and (min-width:640px) and (max-width:719px){html{font-size:20px}} @media screen and (min-width:720px) and (max-width:749px){html{font-size:22.5px}} @media screen and (min-width:750px) and (max-width:799px){html{font-size:23.5px}} @media screen and (min-width:800px){html{font-size:25px}}
//在get時,若是是JSON格式,那麼將其轉換爲JSON,而不是字符串。如下是基礎代碼: var Store = { get: function(key) { var value = localStorage.getItem(key); if (value) { try { var value_json = JSON.parse(value); if (typeof value_json === 'object') { return value_json; } else if (typeof value_json === 'number') { return value_json; } } catch(e) { return value; } } else { return false; } }, set: function(key, value) { localStorage.setItem(key, value); }, remove: function(key) { localStorage.removeItem(key); }, clear: function() { localStorage.clear(); } };
在此基礎之上,能夠擴展不少方法,好比批量保存或刪除一些數據:
// 批量保存,data是一個字典 Store.setList = function(data) { for (var i in data) { localStorage.setItem(i, data[i]); } }; // 批量刪除,list是一個數組 Store.removeList = function(list) { for (var i = 0, len = list.length; i < len; i++) { localStorage.removeItem(list[i]); } };
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title></title> <script src=""></script> <style type="text/css"> * { padding: 0px; margin: 0px; } #main { width: 100%; height: 2000px; background: pink; } </style> <script type="text/javascript"> $(window).scroll(function() { var scrollTop = $(this).scrollTop(); var docHeight = $(document).height(); var windowHeight = $(this).height(); var scrollHeight=document.body.scrollHeight; console.log("scrollTop:"+scrollTop); console.log("scrollbottom:"+(docHeight-scrollTop-windowHeight)); if(scrollTop + windowHeight == docHeight) { alert("已經到最底部了!"); } }); </script> </head> <body> <div id="main"></div> </body> </html>
JS設置cookie:
假設在A頁面中要保存變量username的值("jack")到cookie中,key值爲name,則相應的JS代碼爲: document.cookie="name="+username; JS讀取cookie: 假設cookie中存儲的內容爲:name=jack;password=123 則在B頁面中獲取變量username的值的JS代碼以下: var username=document.cookie.split(";")[0].split("=")[1]; //JS操做cookies方法! //寫cookies function setCookie(name,value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days*24*60*60*1000); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } //讀取cookies function getCookie(name) { var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return unescape(arr[2]); else return null; } //刪除cookies function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString(); } //使用示例 setCookie("name","hayden"); alert(getCookie("name")); //若是須要設定自定義過時時間 //那麼把上面的setCookie 函數換成下面兩個函數就ok; //程序代碼 function setCookie(name,value,time) { var strsec = getsec(time); var exp = new Date(); exp.setTime(exp.getTime() + strsec*1); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } function getsec(str) { alert(str); var str1=str.substring(1,str.length)*1; var str2=str.substring(0,1); if (str2=="s") { return str1*1000; } else if (str2=="h") { return str1*60*60*1000; } else if (str2=="d") { return str1*24*60*60*1000; } } //這是有設定過時時間的使用示例: //s20是表明20秒 //h是指小時,如12小時則是:h12 //d是天數,30天則:d30 setCookie("name","hayden","s20"); /***************************************/ function getCookie(name){ if(name){ var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return (decodeURIComponent(arr[2])); else return null; } return null; }; function setCookie(name,value,Days){ if(!Days)Days=3000; var exp = new Date(); exp.setTime(exp.getTime() + Days*24*60*60*1000000); document.cookie = name + "="+ encodeURIComponent(value) + ";domain=weshare.com.cn;expires=" + exp.toGMTString() + ";path=/"; };
function GetURLlist(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r != null) return unescape(r[2]); return null; };
var u = navigator.userAgent, app = navigator.appVersion; var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android終端或者uc瀏覽器 var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios終端 if(isAndroid){ $(".down0").css('display','none') }else if(isiOS){ $(".down").css('display','none') } else{ return false; }
function isWeiXin(){ var ua = window.navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i) == 'micromessenger'){ return true; }else{ return false; } }
var u = navigator.userAgent; var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1|| u.indexOf('MI') > -1|| <br>u.indexOf('XiaoMi') > -1; //android終端或者uc,小米等奇葩瀏覽器 if(!isAndroid) {} if(isAndroid) {}
<script type="text/javascript"> $(function() { function scroll(fn) { var beforeScrollTop = document.body.scrollTop, fn = fn || function() {}; window.addEventListener("scroll", function() { var afterScrollTop = document.body.scrollTop, delta = afterScrollTop - beforeScrollTop; if(delta === 0) return false; fn(delta > 0 ? "down" : "up"); beforeScrollTop = afterScrollTop; }, false); } scroll(function(direction) { if(direction == "down") { console.log("向下滾"); } else { console.log("向上滾"); } }); }); </script>
<script type="text/javascript"> var windowHeight = $(window).height(); $("body").css("height", windowHeight); var startX, startY, moveEndX, moveEndY, X, Y; $("body").on("touchstart", function(e) { e.preventDefault(); startX = e.originalEvent.changedTouches[0].pageX, startY = e.originalEvent.changedTouches[0].pageY; }); $("body").on("touchmove", function(e) { e.preventDefault(); moveEndX = e.originalEvent.changedTouches[0].pageX, moveEndY = e.originalEvent.changedTouches[0].pageY, X = moveEndX - startX, Y = moveEndY - startY; if (Math.abs(X) > Math.abs(Y) && X > 0) { alert("left to right"); } else if (Math.abs(X) > Math.abs(Y) && X < 0) { alert("right to left"); } else if (Math.abs(Y) > Math.abs(X) && Y > 0) { alert("top to bottom"); } else if (Math.abs(Y) > Math.abs(X) && Y < 0) { alert("bottom to top"); } else { alert("just touch"); } }); </script>
<script type="text/javascript"> var a = [1, 18, 23, 9, 16, 10, 29, 17]; var t = 0; for(var i = 0; i < a.length; i++) { for(var j = i + 1; j < a.length; j++) { if(a[i] > a[j]) { t = a[i]; a[i] = a[j]; a[j] = t; } } } console.log(a); //[1, 9, 10, 16, 17, 18, 23, 29] </script>
<!Doctype html> <html> <head> <meta charset="utf-8"> <title>下班倒計時</title> <style> * { margin: 0; padding: 0; } body { font-size: 16px; text-align: center; font-family: arial; } .time { margin-top: 10px; border: 1px solid red; height: 30px; padding: 2px; line-height: 30px; } </style> </head> <body> <div class="time"> <span id="t_d">00天</span> <span id="t_h">00時</span> <span id="t_m">00分</span> <span id="t_s">00秒</span> </div> <script> setInterval(function() { var EndTime = new Date('2016/06/13 00:00:00'); var NowTime = new Date(); var t = EndTime.getTime() - NowTime.getTime(); var d = 0; var h = 0; var m = 0; var s = 0; if (t >= 0) { d = Math.floor(t / 1000 / 60 / 60 / 24); h = Math.floor(t / 1000 / 60 / 60 % 24); m = Math.floor(t / 1000 / 60 % 60); s = Math.floor(t / 1000 % 60); } document.getElementById("t_d").innerHTML = d + "天"; document.getElementById("t_h").innerHTML = h + "時"; document.getElementById("t_m").innerHTML = m + "分"; document.getElementById("t_s").innerHTML = s + "秒"; }, 10); </script> </body> </html>
function _typeOf(obj) { return Object.prototype.toString.call(obj).toLowerCase().slice(8, -1); // } 判斷undefined: <span style="font-size: small;"> var tmp = undefined; if (typeof(tmp) == "undefined"){ alert("undefined"); } </span> 判斷null: <span style="font-size: small;"> var tmp = null; if (!tmp && typeof(tmp)!="undefined" && tmp!=0){ alert("null"); } </span> 判斷NaN: var tmp = 0/0; if(isNaN(tmp)){ alert("NaN"); } 判斷undefined和null: <span style="font-size: small;"> var tmp = undefined; if (tmp== undefined) { alert("null or undefined"); } </span> <span style="font-size: small;"> var tmp = undefined; if (tmp== null) { alert("null or undefined"); } </span> 判斷undefined、null與NaN: <span style="font-size: small;"> var tmp = null; if (!tmp) { alert("null or undefined or NaN"); } </span>
jquery ajax函數javascript
我本身封裝了一個ajax的函數,代碼以下:php
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方式css
有時候咱們爲了跨域,要使用jsonp的方法,我也封裝了一個函數:html
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(){ //錯誤處理 } });
var random_str = function() { var len = 32; var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; var max = chars.length; var str = ''; for (var i = 0; i < len; i++) { str += chars.charAt(Math.floor(Math.random() * max)); } return str; }; //這樣生成一個32位的隨機字符串,相同的機率低到不可能。
JavaScript過濾Emoji的最佳實踐java
name = name.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
手機號驗證:node
var validate = function(num) { var reg = /^1[3-9]\d{9}$/; return reg.test(num); };
身份證號驗證:jquery
var reg = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;
ip驗證:android
var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/
返回頂部:ios
$(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'); });
阻止冒泡:css3
function stopBubble(e){ e = e || window.event; if(e.stopPropagation){ e.stopPropagation(); //W3C阻止冒泡方法 }else { e.cancelBubble = true; //IE阻止冒泡方法 } }
所有替換replaceAll:
var replaceAll = function(bigStr, str1, str2) { //把bigStr中的全部str1替換爲str2 var reg = new RegExp(str1, 'gm'); return bigStr.replace(reg, str2); }
獲取瀏覽器url中的參數值:
var getURLParam = function(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null; };
深度拷貝對象:
function cloneObj(obj) { var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf()); for(var key in obj){ if(o[key] != obj[key] ){ if(typeof(obj[key]) == 'object' ){ o[key] = mods.cloneObj(obj[key]); }else{ o[key] = obj[key]; } } } return o; }
數組去重:
var unique = function(arr) { var result = [], json = {}; for (var i = 0, len = arr.length; i < len; i++){ if (!json[arr[i]]) { json[arr[i]] = 1; result.push(arr[i]); //返回沒被刪除的元素 } } return result; };
判斷數組元素是否重複:
var isRepeat = function(arr) { //arr是否有重複元素 var hash = {}; for (var i in arr) { if (hash[arr[i]]) return true; hash[arr[i]] = true; } return false; };
生成隨機數:
function randombetween(min, max){ return min + (Math.random() * (max-min +1)); }
操做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 ''; };
數據類型: underfined、null、0、false、NaN、空字符串。他們的邏輯非結果均爲true。
閉包格式: 好處:避免命名衝突(全局變量污染)。
(function(a, b) { console.log(a+b); //30 })(10, 20);
截取和清空數組:
var arr = [12, 222, 44, 88]; arr.length = 2; //截取,arr = [12, 222]; arr.length = 0; //清空,arr will be equal to [].
獲取數組的最大最小值:
var numbers = [5, 45822, 120, -215]; var maxInNumbers = Math.max.apply(Math, numbers); //45822 var minInNumbers = Math.min.apply(Math, numbers); //-215
浮點數計算問題:
0.1 + 0.2 == 0.3 //false
爲何呢?由於0.1+0.2等於0.30000000000000004。JavaScript的數字都遵循IEEE 754標準構建,在內部都是64位浮點小數表示。能夠經過使用toFixed()
來解決這個問題。
數組排序sort函數:
var arr = [1, 5, 6, 3]; //數字數組 arr.sort(function(a, b) { return a - b; //從小到大排 return b - a; //從大到小排 return Math.random() - 0.5; //數組洗牌 });
var arr = [{ //對象數組 num: 1, text: 'num1' }, { num: 5, text: 'num2' }, { num: 6, text: 'num3' }, { num: 3, text: 'num4' }]; arr.sort(function(a, b) { return a.num - b.num; //從小到大排 return b.num - a.num; //從大到小排 });
對象和字符串的轉換:
var obj = {a: 'aaa', b: 'bbb'}; var objStr = JSON.stringify(obj); // "{"a":"aaa","b":"bbb"}" var newObj = JSON.parse(objStr); // {a: "aaa", b: "bbb"}
var obj = { name: 'xiaoming', age: 23 }; var newObj = obj; newObj.name = 'xiaohua'; console.log(obj.name); // 'xiaohua' console.log(newObj.name); // 'xiaohua'
上方咱們將obj對象賦值給了newObj對象,從而改變newObj的name屬性,可是obj對象的name屬性也被篡改,這是由於實際上newObj對象得到的只是一個內存地址,而不是真正 的拷貝,因此obj對象被篡改。
var obj2 = { name: 'xiaoming', age: 23 }; var newObj2 = Object.assign({}, obj2, {color: 'blue'}); newObj2.name = 'xiaohua'; console.log(obj2.name); // 'xiaoming' console.log(newObj2.name); // 'xiaohua' console.log(newObj2.color); // 'blue'
上方利用Object.assign()方法進行對象的深拷貝能夠避免源對象被篡改的可能。由於Object.assign() 方法能夠把任意多個的源對象自身的可枚舉屬性拷貝給目標對象,而後返回目標對象。
var obj3 = { name: 'xiaoming', age: 23 }; var newObj3 = Object.create(obj3); newObj3.name = 'xiaohua'; console.log(obj3.name); // 'xiaoming' console.log(newObj3.name); // 'xiaohua'
咱們也可使用Object.create()方法進行對象的拷貝,Object.create()方法能夠建立一個具備指定原型對象和屬性的新對象。
git使用以前的配置:
1.git config --global user.email xxx@163.com 2.git config --global user.name xxx 3.ssh-keygen -t rsa -C xxx@163.com(郵箱地址) // 生成ssh 4.找到.ssh文件夾打開,使用cat id_rsa.pub //打開公鑰ssh串 5.登錄github,settings - SSH keys - add ssh keys (把上面的內容所有添加進去便可)
說明:而後這個郵箱(xxxxx@gmail.com)對應的帳號在github上就有權限對倉庫進行操做了。能夠盡情的進行下面的git命令了。
git經常使用命令:
一、git config user.name / user.email //查看當前git的用戶名稱、郵箱
二、git clone https://github.com/jarson7426/javascript.git project //clone倉庫到本地。
三、修改本地代碼,提交到分支: git add file / git commit -m 「新增文件」 四、把本地庫推送到遠程庫: git push origin master 五、查看提交日誌:git log -5 六、返回某一個版本:git reset --hard 123 七、分支:git branch / git checkout name / git checkout -b dev 八、合併name分支到當前分支:git merge name / git pull origin 九、刪除本地分支:git branch -D name 十、刪除遠程分支: git push origin :daily/x.x.x 十一、git checkout -b mydev origin/daily/1.0.0 //把遠程daily分支映射到本地mydev分支進行開發 十二、合併遠程分支到當前分支 git pull origin daily/1.1.1 1三、發佈到線上: git tag publish/0.1.5 git push origin publish/0.1.5:publish/0.1.5 1四、線上代碼覆蓋到本地: git checkout --theirs build/scripts/ddos git checkout --theirs src/app/ddos
判斷是否有中文:
var reg = /.*[\u4e00-\u9fa5]+.*$/; reg.test('123792739測試') //true
判斷是對象仍是數組:
function isArray = function(o) { return toString.apply(o) === '[object Array]'; } function isObject = function(o) { return toString.apply(o) === '[object Object]'; }
CSS修改滾動條樣式:
::-webkit-scrollbar { width: 10px; background-color: #ccc; } ::-webkit-scrollbar-track { background-color: #ccc; border-radius: 10px; } ::-webkit-scrollbar-thumb { background-color: rgb(255, 255, 255); background-image: -webkit-gradient(linear, 40% 0%, 75% 84%, from(rgb(77, 156, 65)), color-stop(0.6, rgb(84, 222, 93)), to(rgb(25, 145, 29))); border-radius: 10px; }
單行多行省略號:
<style type="text/css"> .inaline { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; /*clip 修剪文本。*/ } .intwoline { display: -webkit-box !important; overflow: hidden; text-overflow: ellipsis; word-break: break-all; -webkit-box-orient: vertical; -webkit-line-clamp: 3; } </style>
遮罩:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>RGBA 遮罩</title> <style type="text/css"> * { padding: 0px; margin: 0px; } html, body { width: 100%; min-height: 100%; background: white; } div.mask { display: none; position: fixed; top: 0px; left: 0px; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); } div.masks-body { width: 300px; height: 300px; position: absolute; top: 0px; left: 0px; bottom: 0px; right: 0px; background: green; margin: auto; } p { position: absolute; width: 30px; height: 30px; background: red; right: 0px; top: -30px; } </style> <script type="text/javascript"> window.onload = function() { document.querySelector("#main").onclick = function() { document.querySelector(".mask").style.display = "block"; } document.querySelector("p#close").onclick=function(){ document.querySelector(".mask").style.display = "none"; } } </script> </head> <body> <button id="main">點我</button> <div class="mask"> <div class="masks-body"> <p id="close"></p> </div> </div> </body> </html>
常見頁面flex佈局:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title></title> <style type="text/css"> * { padding: 0px; margin: 0px; } html, body { width: 100%; min-height: 100%; min-width: 1200px; overflow-x: hidden; } h1 { color: red; text-align: center; } #main0 { height: 400px; background: black; display: flex; flex-flow: row wrap; justify-content: flex-start; align-items: flex-start; } #main0 div:nth-child(2n) { flex: 1; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: red; } #main0 div:nth-child(2n+1) { flex: 1; height: 200px; line-height: 200px; font-size: 100px; text-align: center; background: blue; } #main1 { height: 400px; background: pink; display: flex; flex-flow: row nowrap; justify-content: flex-start; align-items: flex-start; } #main1 div:nth-child(2n) { flex: 1; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: red; } #main1 div:nth-child(2n+1) { width: 300px; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: blue; } #main2 { height: 400px; background: yellow; display: flex; flex-flow: row nowrap; justify-content: flex-start; align-items: flex-start; } #main2 div:nth-child(2n) { flex: 1; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: red; } #main2 div:nth-child(2n+1) { width: 300px; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: blue; } #main3 { height: 400px; background: fuchsia; display: flex; flex-flow: row nowrap; justify-content: flex-start; align-items: flex-start; } #main3 div.div1 { flex: 1; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: blue; } #main3 div.div2 { flex: 2; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: red; } #main3 div.div3 { flex: 3; height: 200px; font-size: 100px; line-height: 200px; text-align: center; background: orange; } </style> </head> <body> <h1>等分佈局</h1> <div id="main0"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div> <h1>左邊固定右邊自適應佈局</h1> <div id="main1"> <div>1</div> <div>2</div> </div> <h1>左右固定中間自適應佈局</h1> <div id="main2"> <div>1