##新打開窗口javascript
利用form標籤css
如利用如下的HTMLhtml
<form method="get" target="_blank" action="http://www.baidu.com/" id="g-form"> <input type="hidden" name="keywords3" value="123"> </form>
當要打開新的窗口,把以上的HTML插入到<body/>裏,而後賦值好input[type=hidden]的參數,再觸發form.submit()方法。(不能直接在action賦值爲一個帶參數的URL,而是利用input[type=hidden])java
利用window.open方法jquery
這個能夠查看window.open方法的API來css3
##檢測是否支持transitiongit
var supportTransition = (function() { var s = document.createElement('p').style, r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s; s = null; return r; })();
##檢測是否已安裝flash及版本github
// 檢測是否已經安裝flash,檢測flash的版本 var flashVersion = (function() { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (ex) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash') .GetVariable('$version'); } catch (ex2) { version = '0.0'; } } version = version.match(/\d+/g); return parseFloat(version[0] + '.' + version[1], 10); })();
##判斷瀏覽器是否支持圖片的base64web
(function() { var data = new Image(); var support = true; data.onload = data.onerror = function() { if (this.width != 1 || this.height != 1) { support = false; } window.isSupportBase64 = support; }; data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; })();
經過不停檢查它的父節點有沒有document元素便可chrome
#檢查元素是否在文檔中 checkIfInDocument = (dom)-> if !dom return false curParent = dom.parentNode inDoc = null recur = -> if null == curParent inDoc = false else if "html" == curParent.tagName.toLowerCase() inDoc = true else curParent = curParent.parentNode recur() recur() return inDoc
var rePhone = /^(13|14|15|17|18)\d{9}$/;
/* @param {number} s: 秒數 */ function arrive_timer_format(s) { var t, hour, min, sec, day; if (s > -1) { hour = Math.floor(s / 3600); min = Math.floor(s / 60) % 60; sec = s % 60; day = parseInt(hour / 24); if (day > 0) { hour = hour - 24 * day; t = day + "day " + hour + ":"; } else t = hour + ":"; if (min < 10) { t += "0"; } t += min + ":"; if (sec < 10) { t += "0"; } t += sec; } return [day, hour, min, sec, t]; }
// 智能適配圖片在容器的位置、大小 // 注意事項,每一個img的父容器必定要有大小 // 不少時候沒注意,加了個寬度和高度都爲0的a標籤,這時要把a設爲display:block; function autoAdjustImg(imgSelector) { var $imgs = $(imgSelector), adjust = function($img, $wrap) { var wrapW = $wrap.width(), wrapH = $wrap.height(), wrapRatio = wrapW / wrapH, imgW = $img.width(), imgH = $img.height(), imgRatio = imgW / imgH, adjustW = function() { $img.css({ width: wrapW + 'px', height: 'auto', marginTop: (wrapH - wrapW / imgW * imgH) / 2 + 'px' }); }, adjustH = function() { $img.css({ height: wrapH + 'px', width: 'auto', marginLeft: (wrapW - wrapH / imgH * imgW) / 2 + 'px' }); }, adjustRect = function() { $img.css({ marginLeft: (wrapW - imgW) / 2 + 'px', marginTop: (wrapH - imgH) / 2 + 'px' }); }; if (imgW > wrapW && imgH > wrapH) { if (wrapRatio > imgRatio) { // 證實是圖片的高度較大 adjustH(); } else { // 圖片的寬度較大 adjustW(); } } else if (imgW > wrapW) { adjustW(); } else if (imgH > wrapH) { adjustH(); } else { adjustRect(); } $img[0]._autoAdjusted = true; }; $.each($imgs, function(i, img) { var $curImg = $(img), $curWrap = $curImg.parent(); if (img.complete) { adjust($curImg, $curWrap); } else { img.onload = function() { adjust($curImg, $curWrap); }; } }); }
這個方法已集成在本人開發的彈窗插件中:查看連接jquery.popup.js
這個是個比較好的方法,一個彈出窗口,要設定在任何其餘地方點擊這個窗口會自動消失,但點這個窗口內部是沒事的。那麼就要用到這個方法了。->即用於檢查是否點擊了目標窗口而觸發的bodyclic事件,若是是,你就能夠另做處理了。
function clickBodyUnlessById(evt, id){ // 是否爲普通的Body點擊事件,true->普通事件,false->點擊到目標ID的Dom了 return id === evt.target.id || $(evt.target).parents(['#', id].join('')).length?!1:!0; }
#免疫bodyclick clickBodyUnlessByDom = (evt, dom)-> $dom = $(dom) specialId = "__kobe_special_id_zzzz__" if !$dom.prop("id") $dom.prop("id", specialId) id = $dom.prop("id") #是否爲普通body點擊事件, true->普通事件, false->點擊到目標dom了 if id == evt.target.id isNormal = false else if $(evt.target).parents("#"+id).length isNormal = false else isNormal = true if specialId == id $dom.attr("id", null) return isNormal
// 通常用法 $(document).on("click", function(evt){ if(false === clickBodyUnlessById(evt, 'test')) return; // 經過id // if(false === clickBodyUnlessByDom(evt, $("div#test"))) return; // (可選)經過Dom $("#test").remove(); });
# 直接讀取location來轉換URL參數 urlParamToObj = ()-> if location.search u = location.search else u = location.href u = u.slice(0, u.indexOf("#")) p = {} if -1 != u.indexOf("?") sear = u.slice(u.indexOf("?")+1).split("&") for item in sear do(item)-> s = item.split("=") p[s[0]] = s[1] return p
##數組去重
//此方法充分利用了遞歸和indexOf方法,感謝網友@真愛像深藍 var unique = function(arr, newArr) { var num; if (-1 == arr.indexOf(num = arr.shift())) newArr.push(num); arr.length && unique(arr, newArr); }
##數據求交集
var intersection = function(array1, array2) { return array1.filter(function(n) { return array2.indexOf(n) != -1; }); }
貌似本方法未做嚴謹處理,好比處理Date,RegExp,function的狀況。若是確認只是普通使用場景,克隆對象不存在上面的狀況,那麼可放心使用本方法
簡版:
function clone(src){ var dist; switch(typeof src){ case "object": if(src instanceof Array){ dist = []; for(var i=0,j=src.length; j>i; i++){ dist.push(clone(src[i])); } }else if (null !== src){ dist = {}; for(var key in src){ dist[key] = clone(src[key]); } }else{ dist = src; } break; default: dist = src; } return dist; }
原版:
function clone(obj) { var o; switch (typeof obj) { case 'undefined': break; case 'string': o = obj + ''; break; case 'number': o = obj - 0; break; case 'boolean': o = obj; break; case 'object': if (obj === null) { o = null; } else { if (obj instanceof Array) { o = []; for (var i = 0, len = obj.length; i < len; i++) { o.push(clone(obj[i])); } } else { o = {}; for (var k in obj) { o[k] = clone(obj[k]); } } } break; default: o = obj; break; } return o; }
var reEmail = /^(?:\w+\.)*\w+@\w+(?:\.\w+)+$/i; reEmail.test( "abc@abc.com" ), // true reEmail.test( "abc.@abc.com" ), // false reEmail.test( "abc.def@abc.com" ), // true reEmail.test( "abc@abc.def.cn" ); // true
Math.guid = function(){ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c){ var r = Math.random()*16|0, v = c == "x" ? r : (r&0x3|0x8); return v.toString(16); }).toUpperCase(); };
function generateRandomAlphaNum(len) { var rdmString = ""; for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2)); return rdmString.substr(0, len); } // 譯者注:特地查了一下Math.random()生成0到1之間的隨機數,number.toString(36)是將這個數字轉換成36進制(0-9,a-z),最後substr去掉前面的「0.」字符串
function base64Encode(str) { return btoa(unescape(encodeURIComponent(str))); } function base64Decode(str) { return decodeURIComponent(escape(atob(str))); }
function getStyle(obj, attribute) { return obj.currentStyle ? obj.currentStyle[attribute] : document.defaultView.getComputedStyle(obj, null)[attribute]; } //IE: var bgColor = oDiv.currentStyle.backgroundColor; //只讀的,若是對它進行寫入會發生錯誤 //DOM: //getComputedStyle(obj,null)接受兩個參數,須要獲取樣式的元素和諸如:hover和:first-letter之類的僞元素 var bgColor = document.defaultView.getComputedStyle(oDiv, null).backgroundColor;
function addCommas(nStr) { nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(d+)(d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }
window.requestAnimFrame = function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(e, t) { return window.setTimeout(e, 1e3 / 60) }; }();
s = new String(" -- kobe ").trim();// -> "-- kobe" s = new String(" -- kobe ").trimLeft();// -> "-- kobe " s = new String(" -- kobe ").trimRight();// -> " -- kobe" // 正則實現trim() function trim(a) {return a.replace(/(^\s*)|(\s*$)/g, "")} // jquery $.trim(" haha ");
//瀏覽器判斷,使用方法: var userAgent = navigator.userAgent.toLowerCase(); browser = { version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1], safari: /webkit/.test(userAgent), opera: /opera/.test(userAgent), chrome: /chrome/.test(userAgent), msie: /msie/.test(userAgent) && !/opera/.test(userAgent), mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent) } //判斷IE6 function isIe6() { if (browser.msie && browser.version == '6.0') { alert('他就是IE6'); } else { alert('不是IE6'); } } isIe6();
jQuery方法:
/* <![CDATA[ */ $(document).ready(function() { var bro = $.browser; var binfo = ""; if (bro.msie) { binfo = "Microsoft Internet Explorer " + bro.version; } if (bro.mozilla) { binfo = "Mozilla Firefox " + bro.version; } if (bro.safari) { binfo = "Apple Safari " + bro.version; } if (bro.opera) { binfo = "Opera " + bro.version; } //alert(binfo); $("#browser").html(binfo); }) /* ]]> */
var prefix = (function() { if ("undefined" !== typeof window.getComputedStyle) { var styles = window.getComputedStyle(document.documentElement, ''), pre = (Array.prototype.slice .call(styles) .join('') .match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o']) )[1], dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1]; return { dom: dom, lowercase: pre, css: '-' + pre + '-', js: pre[0].toUpperCase() + pre.substr(1) }; } })();
輸出有:
{"dom":"WebKit","lowercase":"webkit","css":"-webkit-","js":"Webkit"} {"dom":"MS","lowercase":"ms","css":"-ms-","js":"Ms"} {"dom":"Moz","lowercase":"moz","css":"-moz-","js":"Moz"}
/* * 頻率控制 返回函數連續調用時,fn 執行頻率限定爲每多少時間執行一次 * @param fn {function} 須要調用的函數 * @param delay {number} 延遲時間,單位毫秒 * @param immediate {bool} 給 immediate參數傳遞false 綁定的函數先執行,而不是delay後後執行。 * @return {function} 實際調用函數 */ function throttle(fn, delay, immediate, debounce) { var curr = +new Date(), //當前時間 last_call = 0, last_exec = 0, timer = null, diff, //時間差 context, //上下文 args, exec = function() { last_exec = curr; fn.apply(context, args); }; return function() { curr = +new Date(); context = this, args = arguments, diff = curr - (debounce ? last_call : last_exec) - delay; clearTimeout(timer); if (debounce) { if (immediate) { timer = setTimeout(exec, delay); } else if (diff >= 0) { exec(); } } else { if (diff >= 0) { exec(); } else if (immediate) { timer = setTimeout(exec, -diff); } } last_call = curr; } } /* * 空閒控制 返回函數連續調用時,空閒時間必須大於或等於 delay,fn 纔會執行 * @param fn {function} 要調用的函數 * @param delay {number} 空閒時間 * @param immediate {bool} 給 immediate參數傳遞false 綁定的函數先執行,而不是delay後後執行。 * @return {function} 實際調用函數 */ function debounce(fn, delay, immediate) { return throttle(fn, delay, immediate, true); } /* 調用控制 * 每次調用都會延遲執行fn,直至再也不調用後再延遲執行 * @param fn {function} 要調用的函數 * @param delay {number} 延遲時間 */ function debounceLast(fn, delay){ var timer, delay = delay || 100, _this, args; return function(){ if(timer){ clearTimeout(timer); } _this = this, args = arguments; timer = setTimeout(function(){ fn.apply(_this, args); timer = null; }, delay); } }
簡單來講,假設設置了delay爲1秒,若是連續不停快速觸發fn,throttle會每秒觸發一次fn,由於頻率控制在最多每秒觸發1次; 而debounce第一秒後觸發fn,以後都不會觸發fn,由於至少要1秒的空閒時間才能夠繼續觸發fn; 而debounceLast的方法一直被觸發的話那一直都不會執行,直至中止觸發後才延遲delay毫秒後執行
:hover
, :active
, :before
……
var bgcolor = window.getComputedStyle( document.querySelector('.element'), ':before' ).getPropertyValue('background-color'); var aFontSize = window.getComputedStyle(document.getElementById("a"), ":hover").fontSize;
typeof
:不能很好判斷obj, null , arr, regexp和自定義對象constructor
: 支持大部分對象類型判斷,特別是自定義類型對象,但不能在null和undefined上使用Object.prototype.toString.call()
:支持絕大多數類型判斷,但不支持自定義類型對象var toString = Object.prototype.toString; console.log(toString.call(arr)); // [object Array] console.log(toString.call(nullObj)); //[object Null] console.log(toString.call(user)); // [object Object]不能做進一步的判斷
爲何不直接用obj.toString()?由於obj.toString()返回的是其對象的內容,如數值,字符串,數組等內容,很差作判斷
總結:推薦使用Object.prototype.toString.call()
方法,由於他能解決絕大部分狀況的判斷,在遇到返回值爲[object Object]
時,再使用constructor
輔助判斷,看是不是自定義對象。
'ontouchstart' in document.documentElement
if (!Function.prototype.bind) { Function.prototype.bind = function(obj) { var slice = [].slice, args = slice.call(arguments, 1), self = this, nop = function() {}, bound = function() { return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments))); }; nop.prototype = self.prototype; bound.prototype = new nop(); return bound; }; }
在目標區域在屏幕中可見時,它的行爲就像position:relative;而當頁面滾動超出目標區域時,它的表現就像position:fixed,它會固定在目標位置。
position:sticky
是一個新的css3屬性,它的表現相似position:relative
和position:fixed
的合體,在目標區域在屏幕中可見時,它的行爲就像position:relative;而當頁面滾動超出目標區域時,它的表現就像position:fixed,它會固定在目標位置。
HTML5瀏覽器實現:
.sticky { position: -webkit-sticky; position:sticky; top: 15px; } ··· 其餘瀏覽器實現: ```html <style> .sticky { position: fixed; top: 0; } .header { width: 100%; background: #F6D565; padding: 25px 0; } </style> <div class="header"></div> <script> var header = document.querySelector('.header'); var origOffsetY = header.offsetTop; function onScroll(e) { window.scrollY >= origOffsetY ? header.classList.add('sticky') : header.classList.remove('sticky'); } document.addEventListener('scroll', onScroll); </script>
##字符串長度截取
function cutstr(str, len) { var temp, icount = 0, patrn = /[^\x00-\xff]/, strre = ""; for (var i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr(i, 1); if (patrn.exec(temp) == null) { icount = icount + 1 } else { icount = icount + 2 } strre += temp } else { break; } } return strre + "..." }
##字符串替換所有
String.prototype.replaceAll = function(s1, s2) { return this.replace(new RegExp(s1, "gm"), s2) }
##轉義html標籤
function HtmlEncode(text) { return text.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>') }
##時間日期格式轉換
Date.prototype.Format = function(formatStr) { var str = formatStr; var Week = ['日', '一', '二', '三', '四', '五', '六']; str = str.replace(/yyyy|YYYY/, this.getFullYear()); str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100)); str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1)); str = str.replace(/M/g, (this.getMonth() + 1)); str = str.replace(/w|W/g, Week[this.getDay()]); str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate()); str = str.replace(/d|D/g, this.getDate()); str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours()); str = str.replace(/h|H/g, this.getHours()); str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes()); str = str.replace(/m/g, this.getMinutes()); str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds()); str = str.replace(/s|S/g, this.getSeconds()); return str }
##加入收藏夾
function AddFavorite(sURL, sTitle) { try { window.external.addFavorite(sURL, sTitle) } catch (e) { try { window.sidebar.addPanel(sTitle, sURL, "") } catch (e) { alert("加入收藏失敗,請使用Ctrl+D進行添加") } } }
##設爲首頁
function setHomepage() { if (document.all) { document.body.style.behavior = 'url(#default#homepage)'; document.body.setHomePage('http://w3cboy.com') } else if (window.sidebar) { if (window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect") } catch (e) { alert("該操做被瀏覽器拒絕,若是想啓用該功能,請在地址欄內輸入 about:config,而後將項 signed.applets.codebase_principal_support 值該爲true") } } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage', 'http://w3cboy.com') } }
##關閉網頁時警告
window.onbeforeunload = function(){ return "真的要離開?"; };
##解綁匿名函數事件
利用arguments.callee
document.body.addEventListener("click", function(){ alert("clicked!"); document.body.removeEventListener("click", arguments.callee, false); }, false);