/** 獲取元素到頁面頂端的距離(出自jquery源碼) */ function getCoords(el) { if (typeof el == 'string') { el = Fid(el); } var box = el.getBoundingClientRect(), doc = el.ownerDocument, body = doc.body, html = doc.documentElement, clientTop = html.clientTop || body.clientTop || 0, clientLeft = html.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || html.scrollTop || body.scrollTop) - clientTop, left = box.left + (self.pageXOffset || html.scrollLeft || body.scrollLeft) - clientLeft return { 'top' : top, 'left' : left }; }; /* 獲取元素到頁面頂端的 document.documentElement.clientLeft ie6/7 下2px的bodrer */ function getAbsPoint(e) { if (typeof e == 'string') { e = Fid(e); } var x = e.offsetLeft; var y = e.offsetTop; var de = document.documentElement; while (e = e.offsetParent) { //在IE下offset對象是對當前元素到上一級元素的距離,FF則是正常的 x += e.offsetLeft; y += e.offsetTop; //需要加上元素自身的border, offsetTop 本身就包含margin if (e && e != de && !Browser.isOpera) { x += e.clientLeft; y += e.clientTop; //ie6下設置元素寬度后才能到獲取他的邊框大小,如果不設置則下級取上級的時候會把上級的邊框算進去(總體計算還是沒有錯) } } return { "left" : x, "top" : y }; }
//瀏覽器類型檢測 var FBrowser=(function(){ var ua = navigator.userAgent; var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; return { isIE: !!window.attachEvent && window.ActiveXObject && !isOpera, isOpera: isOpera, isSafari: ua.indexOf('AppleWebKit/') > -1, isFirefox: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, MobileSafari: /Apple.*Mobile.*Safari/.test(ua), isChrome: !!window.chrome, }; })(); FBrowser.isIE6=FBrowser.isIE&&!window.XMLHttpRequest; FBrowser.isIE7=FBrowser.isIE&&!!window.XMLHttpRequest;
//document.documentMode ie8+以上顯示瀏覽器版本 var IE = (function(){ var ie = !!window.ActiveXObject; e = { isIE: !!window.ActiveXObject, isIE6: ie && !window.XMLHttpRequest, isIE7: ie && window.XMLHttpRequest && document.documentMode == 7, isIE8: ie && window.XMLHttpRequest && document.documentMode == 8, isIE9: ie && window.XMLHttpRequest && document.documentMode == 9 } return e; })();
/** 獲取元素樣式 處理透明度、元素浮動樣式的獲取 ,結果帶有單位 */ function getStyle(elem, name) { var nameValue = null; if (document.defaultView) { var style = document.defaultView.getComputedStyle(elem, null); nameValue = name in style ? style[name] : style.getPropertyValue(name); } else { var style = elem.style, curStyle = elem.currentStyle; //透明度 from youa if (name == "opacity") { if (/alpha\(opacity=(.*)\)/i.test(curStyle.filter)) { var opacity = parseFloat(RegExp.$1); return opacity ? opacity / 100 : 0; } return 1; } if (name == "float") { name = "styleFloat"; } var ret = curStyle[name] || curStyle[camelize(name)]; //單位轉換 from jqury if (!/^-?\d+(?:px)?$/i.test(ret) && /^\-?\d/.test(ret)) { var left = style.left, rtStyle = elem.runtimeStyle, rsLeft = rtStyle.left; rtStyle.left = curStyle.left; style.left = ret || 0; ret = style.pixelLeft + "px"; style.left = left; rtStyle.left = rsLeft; } nameValue = ret; } return nameValue === 'auto' ? '0px' : nameValue; } function uncamelize(s) {//將CSS屬性名由駝峰式轉為普通式 return s.replace(/[A-Z]/g,function (c) { return '-'+c.charAt(0).toLowerCase(); }); } function camelize(s) {//將CSS屬性名轉換成駝峰式 return s.replace(/-[a-z]/gi,function (c) { return c.charAt(1).toUpperCase(); }); }
function each( object, callback ) { if ( undefined === object.length ){ for ( var name in object ) { if (false === callback( object[name], name, object )) break; } } else { for ( var i = 0, len = object.length; i < len; i++ ) { if (i in object) { if (false === callback( object[i], i, object )) break; } } } }
//獲取scrolltop function getScrollTop() { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; return scrollTop; } //設置scrolltop function setScrollTop(top) { document.documentElement.scrollTop = document.body.scrollTop = top; }
/** 獲取瀏覽器可視區域的尺寸 */ function getBrowserSize() { //在標准模式下用 documentElement, 在怪癖模式下用 body return { width:document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth, height:document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight, } }
/** 獲取頁面大小 */ function getPageSize() { //ie下優先取 body return { width:document.body.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth, height: document.body.scrollHeight ? document.body.scrollHeight : document.documentElement.scrollHeight } }
/** * 根據類名獲取元素 * * @param className * @param context * @returns */ function getByClassName(className,context) { context=context || document; if (context.getElementsByClassName) { return context.getElementsByClassName(className); } var nodes=context.getElementsByTagName('*'),ret=[]; for (var i=0;i<nodes.length;i++) { if (nodes[i].nodeType == 1 && nodes[i].className.indexOf(className) != -1) { ret.push(nodes[i]); } } return ret; }
/** * Registers a callback for DOM ready. If DOM is already ready, the * callback is called immediately. * @param {Function} Array callback */ function domReady(callback) { var isTop, testDiv, scrollIntervalId, isPageLoaded = false, doc = document, readyCalls = []; function runCallbacks(callbacks) { var i; for (i = 0; i < callbacks.length; i += 1) { callbacks[i](doc); } } function callReady() { var callbacks = readyCalls; if (isPageLoaded) { //Call the DOM ready callbacks if (callbacks.length) { readyCalls = []; runCallbacks(callbacks); } } } /** * Sets the page as loaded. */ function pageLoaded() { if (!isPageLoaded) { isPageLoaded = true; if (scrollIntervalId) { clearInterval(scrollIntervalId); } callReady(); } } if (document.addEventListener) { //Standards. Hooray! Assumption here that if standards based, //it knows about DOMContentLoaded. document.addEventListener("DOMContentLoaded", pageLoaded, false); window.addEventListener("load", pageLoaded, false); } else if (window.attachEvent) { window.attachEvent("onload", pageLoaded); testDiv = document.createElement('div'); try { isTop = window.frameElement === null; } catch (e) {} //DOMContentLoaded approximation that uses a doScroll, as found by //Diego Perini: http://javascript.nwbox.com/IEContentLoaded/, //but modified by other contributors, including jdalton if (testDiv.doScroll && isTop && window.external) { scrollIntervalId = setInterval(function () { try { testDiv.doScroll(); pageLoaded(); } catch (e) {} }, 1); } } //Check if document already complete, and if so, just trigger page load //listeners. Latest webkit browsers also use "interactive", and //will fire the onDOMContentLoaded before "interactive" but not after //entering "interactive" or "complete". More details: //http://dev.w3.org/html5/spec/the-end.html#the-end //http://stackoverflow.com/questions/3665561/document-readystate-of-interactive-vs-ondomcontentloaded //Hmm, this is more complicated on further use, see "firing too early" //bug: https://github.com/requirejs/domReady/issues/1 //so removing the || document.readyState === "interactive" test. //There is still a window.onload binding that should get fired if //DOMContentLoaded is missed. if (document.readyState === "complete") { pageLoaded(); } if (isPageLoaded) {//dom已經ready callback(doc); } else { readyCalls.push(callback); } } domReady(function(){ alert('domload'); alert(document.getElementById('container')); })
//改變某個函數的內部this指針 function closure(fn, scope) { return function (){ fn.apply(scope, arguments); }; } //調用某個對象的某個函數,並將次對象作為方法的作用域 function invoke(obj, methodName) { return function(){ obj.methodName.apply(obj, arguments); }; }
// 元素數據緩存 (function(){ var cache = [0], expando = 'data' + +new Date(); function data(elem) { var cacheIndex = elem[expando], nextCacheIndex = cache.length; if(!cacheIndex) { cacheIndex = elem[expando] = nextCacheIndex; cache[cacheIndex] = {}; } return { get : function(key) { if(typeof key === 'string') { return cache[cacheIndex] ? cache[cacheIndex][key] : null; } return cache[cacheIndex] ? cache[cacheIndex] : null; }, set : function(key, val) { cache[cacheIndex][key] = val; return data(elem); }, remove : function(key){ if(cache[cacheIndex]) { return cache.splice(cacheIndex,1); } } } } window.data = data; })();
//js請求xml文件, if (window.ActiveXObject) { //IE var getXMLDOM=function () { return new ActiveXObject("Microsoft.XmlDom"); },loadXMLFile=function (xmlDom,url,callback) { xmlDom.onreadystatechange=function () { if (xmlDom.readyState===4) { if (xmlDom.parseError.errorCode===0) { callback.call(xmlDom); } else { throw new Error("XML Parse Error:"+xmlDom.parseError.reason); } } }; xmlDom.load(url); return xmlDom; },loadXMLString=function (xmlDom,s) { xmlDom.loadXML(s); if (xmlDom.parseError.errorCode!==0) { throw new Error("XML Parse Error:"+xmlDom.parseError.reason); } return xmlDom; }, getXML=function (xmlNode) { return xmlNode.xml; }; }else if (document.implementation && document.implementation.createDocument) { //W3C var getXMLDOM=function () {//獲取一個XMLDOM對象 return document.implementation.createDocument("","",null); }, loadXMLFile=function (xmlDom,url,callback) { if (xmlDom.async===true) { xmlDom.onload=function () { if (xmlDom.documentElement.nodeName=="parsererror") { throw new Error("XML Parse Error:"+xmlDom.documentElement.firstChild.nodeValue); } else { callback.call(xmlDom); } }; } console.dir(xmlDom); xmlDom.load(url); return xmlDom; }, loadXMLString=function (xmlDom,s) { var p = new DOMParser(); var newDom=p.parseFromString(s,"text/xml"); if (newDom.documentElement.nodeName=="parsererror") { throw new Error("XML Parse Error:"+newDom.documentElement.firstChild.nodeValue); } while (xmlDom.firstChild) { xmlDom.removeChild(xmlDom.firstChild); } for (var i=0,n;i<newDom.childNodes.length;i++) { n=xmlDom.importNode(newDom.childNodes[i],true); //importNode用於把其它文檔中的節點導入到當前文檔中 //true參數同時導入子節點 xmlDom.appendChild(n); } return xmlDom; }, getXML=function (xmlNode) { var s= new XMLSerializer(); return s.serializeToString(xmlNode,"text/xml"); }; } var xmldom = getXMLDOM(); loadXMLFile(xmldom,"/xml.php",function () { alert(this); });
/** args { url method 默認值為get success Function data {key:value} cache Boolean true表示緩存,默認值為false datatype 默認 text text|xml } */ function ajax(args) { //創建xhr對象 function createXHR() { return window.XMLHttpRequest? new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");//IE6 } //拼接參數 function params(o) { var a=[]; for (var i in o) { a.push(encodeURIComponent(i)+"="+encodeURIComponent(o[i])); } return a.join("&"); } var xhr = createXHR(); args.method=args.method || "get"; if (!args.cache) { args.data.cache = (new Date()*1); } var data_str = params(args.data) if (/get/i.test(args.method) && data_str) { args.url += args.url.indexOf("?")<0 ? '?' : '&'; args.url += data_str; } xhr.open(args.method,args.url,true); xhr.onreadystatechange=function () { if (xhr.readyState===4 && xhr.status===200) { if(!args.datatype || args.datatype.toLowerCase() === 'text') { args.success(xhr.responseText); }else{ args.success(xhr.responseXML); } } }; if (/post/i.test(args.method)) { xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(data); } else { xhr.send(); } } ajax({ url:"/xml.php", method:'post', success:function(xmldom){ alert(xmldom.nodeName); }, data:{id:1}, datatype:'xml' })
//獲取firstchild function firstChild(elem) { var node = elem.firstChild ? elem.firstChild : null; while(node && node.nodeType != 1) { node = node.nextSibling; } return node; } //獲取下一個同輩元素(ie下回忽略空白文節點) function next(elem) { var node = elem.nextSibling ? elem.nextSibling : null; while(node && node.nodeType != 1 ) { node = node.nextSibling; } return node; } //獲取上一個同輩元素(ie下回忽略空白文節點) function prev(elem) { var node = elem.previousSibling ? elem.previousSibling : null; while(node && node.nodeType != 1 ) { node = node.previousSibling; } return node; }
/** * 獲取指定類名的父元素 * @param elem * @param className * @returns */ function parents(elem, className) { //檢測自身是否滿足條件 if(elem.className.indexOf(className) != -1) { return elem; } var parent = null; while((parent = elem.parentNode) && parent.nodeType == 1 && !!className) { if(parent.className.indexOf(className) != -1) { break; } elem = parent; } return parent; }
//輸入html代碼,輸出轉換后的代碼 function htmlEncode( html ) { //使用div來模擬 var div = document.createElement("div"); if(typeof div.innerText != 'undefined') { div.innerText = html; }else{ div.textContent = html; } var html_encode = div.innerHTML; div = null; return html_encode; } function htmlDecode( html ) { //使用div來模擬 var text, div = document.createElement("div"); div.innerHTML = html; if(typeof div.innerText != 'undefined') { text = div.innerText; }else{ text = div.textContent; } return text; } function htmlEncode(str) { var s = ""; if (str.length == 0) return ""; s = str.replace(/\&/g, "&"); s = s.replace(/</g, "<"); s = s.replace(/>/g, ">"); s = s.replace(/\'/g, "'"); s = s.replace(/\"/g, """); return s; } function htmlDecode(str) { var s = ""; if (str.length == 0) return ""; s = str.replace(/&/g, "&"); s = s.replace(/</g, "<"); s = s.replace(/>/g, ">"); s = s.replace(/'/g, "\'"); s = s.replace(/"/g, "\""); return s; } function htmlEncode(html) { var div = document.createElement("div"); var text = document.createTextNode(""); div.appendChild(text); text.nodeValue=html; return div.innerHTML; } function htmlDecode(str) { var div = document.createElement("div"); div.innerHTML = str; return div.firstChild.nodeValue; }
//計算數組中的最大值 Array.prototype.max = function(){ return Math.max.apply({},this) } //計算數組中的最小值 Array.prototype.min = function(){ return Math.min.apply({},this) } //復制數組 Array.prototype.copy = function() { return [].concat(this); }; //去除數組中只指定元素,只能去除一個,如果想多個,之前先用unique處理 Array.prototype.remove = function(value){ for(var i=0,len=this.length;i<len;i++) { if(this[i]==value){ this.splice(i, 1); break; } } return this; } //去除數組中只指定元素,只能去除一個,如果想多個,之前先用unique處理 Array.prototype.inArray = function(value){ var index = -1; each(this,function(v,k){ if(v == value){ index = k; return false; } }) return index; } //去除數組中的重復元素 Array.prototype.unique = function(){ var rst = []; each(this, function(v,k){ if(rst.inArray(v)<0) rst.push(v); }) return rst; }
String.prototype.repeat=function(n){return new Array(n+1).join(this);} String.prototype.ltrim=function(){return this.replace(/^\s*/, "");} String.prototype.rtrim=function(){return this.replace(/\s*$/, "");} String.prototype.trim=function(){return this.rtrim().ltrim();} //非ascii字符 String.prototype.hasChinese=function(){return /[^\u00-\uff]/g.test(this);} //包括中英韓文,這三種語言里面有更多共同的 String.prototype.onlyChinese=function(){return /^[\u0391-\u9FBF]+$/g.test(this);} //取得字符串實際長度(漢字算兩個字節,英文字母算一個字節) \x代表ascii碼,會按unicode碼進行匹配 String.prototype.bytes=function(){ return this.replace(/[^\x00-\xff]/gi,'xx').length;} Number.prototype.inter=function (a,b) {//檢測數字是否在區間之內 var min=Math.min(a,b),max=Math.max(a,b); return this==a || this==b || (Math.max(this,min)==this && Math.min(this,max)==this); };
//過濾空白文本節點 function filterSpaceNode(nodes) {掉 var ret=[]; for(var i=0;i<nodes.length;i++) { if (nodes[i].nodeType===3 && /^\s+$/.test(nodes[i].nodeValue)) { continue; } ret.push(nodes[i]); } return ret; }
function addClassName(obj,cn) { return obj.className += " " + cn; } function delClassName(obj,cn) { return obj.className = obj.className.replace(new RegExp("\\b"+cn+"\\b"),""); //同樣,多個className之間的多個空格也會被視為一個 } function hasClassName(obj,cn) { return (new RegExp("\\b"+cn+"\\b")).test(obj.className); }
function placeNode(node,fn,__this) { fn.call(__this,frag(node)); return __this; } function append(node, newNode) { return placeNode(newNode,function (one) {node.appendChild(one)},node); } function preappend(node, newNode) { return placeNode(newNode,function (one) {node.insertBefore(one,node.firstChild)},node); } function before(node, newNode) { return placeNode(newNode,function (one) {node.parentNode.insertBefore(one,node)},node); } function after(node, newNode) { //如果node有下一個節點的話,newNode 插入到node.nextSibling的前面 //如果node沒有下一個節點,newNode插入為node.parentNode的最后一個子 if (node.nextSibling) { placeNode(newNode,function (one) {node.parentNode.insertBefore(one,node.nextSibling)},node); } else { placeNode(newNode,function (one) {node.parentNode.appendChild(one)},node); } return node; }
//如果新節點是頁面中已經存在的則新節點原來的位置會消失 function replaceNode(newNode, node) { node.parentNode.replaceChild(newNode, node); } function delNode(node) { node.parentNode.removeChild(this); } function frag(nodes) { var tempFrag =document.createDocumentFragment(); if (nodes.nodeType) {nodes=[nodes];} /* 錯誤的寫法 傳入的是引用 each(nodes,function(node){ tempFrag.appendChild(node); })*/ for(var i=0;i<nodes.length;i++) { //克隆后不在是引用 var a = nodes[i].cloneNode(true); (function(node){ tempFrag.appendChild(node); })(a) } /* while(nodes.length>0) { tempFrag.appendChild(nodes[0]); alert(nodes.length); } */ return tempFrag; } //html轉換為對象 function html2Obj(html) { var div = document.createElement('div'); div.innerHTML = html; return div.firstChild; }
//數據的本地化存儲,都兼容 function makeWebStorage() { //ie用userdata實現,w3c瀏覽器本身支持 if (!("localStorage" in window)) { var store = { userData : null, name : location.hostname, init : function () { if (!store.userData) { try { store.userData = document.createElement('INPUT'); store.userData.type = "hidden"; store.userData.style.display = "none"; store.userData.addBehavior("#default#userData"); document.body.appendChild(store.userData); var expires = new Date(); expires.setDate(expires.getDate() + 365); store.userData.expires = expires.toUTCString(); } catch (e) { return false; } } return true; }, setItem : function (key, value) { if (store.init()) { store.userData.load(store.name); store.userData.setAttribute(key, value); store.userData.save(store.name); } }, getItem : function (key) { if (store.init()) { store.userData.load(store.name); return store.userData.getAttribute(key) } }, remove : function (key) { if (store.init()) { store.userData.load(store.name); store.userData.removeAttribute(key); store.userData.save(store.name); } } }; }else{ store = { set:function(key, value){localStorage.setItem(key, value)}, get:function(key){return localStorage.getItem(key)}, remove:function(key){return localStorage.removeItem(key)} } } window.webStorage = store; }
/** * 記錄函數調用的次數 */ function invokeTimes(){ if(arguments.callee.times == undefined) { arguments.callee.times = 0; } arguments.callee.times ++; console.log(arguments.callee.times); } document.body.onclick = function(){ invokeTimes(); }
/** *javascript按字節進行截取 * * param str 要截取的字符串 * param L 要截取的字節長度,注意是字節不是字符,一個漢字兩個字節 * return 截取后的字符串 */ function cutStr(str,L){ var result = '', strlen = str.length, // 字符串長度 chrlen = str.replace(/[^\x00-\xff]/g,'**').length; // 字節長度 if(chrlen<=L){return str;} for(var i=0,j=0;i<strlen;i++){ var chr = str.charAt(i); if(/[\x00-\xff]/.test(chr)){ j++; // ascii碼為0-255,一個字符就是一個字節的長度 }else{ j+=2; // ascii碼為0-255以外,一個字符就是兩個字節的長度 } if(j<=L /* || j==L+1 */){ // 當加上當前字符以后,如果總字節長度小於等於L,則將當前字符真實的+在result后 result += chr; }else{ // 反之則說明result已經是不拆分字符的情況下最接近L的值了,直接返回 return result; } } } // 用例 alert(cutStr("abc中英文混合",10));
//變量定義 效果同php中的define函數 function define (name, value) { // Define a new constant // // version: 903.3016 // discuss at: http://phpjs.org/functions/define // + original by: Paulo Freitas // + revised by: Andrea Giammarchi (http://webreflection.blogspot.com) // + reimplemented by: Brett Zamir (http://brett-zamir.me) // * example 1: define('IMAGINARY_CONSTANT1', 'imaginary_value1'); // * results 1: IMAGINARY_CONSTANT1 === 'imaginary_value1' var defn, replace, script, that = this, d = this.window.document; var toString = function (name, value) { return 'const ' + name + '=' + (/^(null|true|false|(\+|\-)?\d+(\.\d+)?)$/.test(value = String(value)) ? value : '"' + replace(value) + '"'); }; try { eval('const e=1'); replace = function (value) { var replace = { "\x08": "b", "\x0A": "\\n", "\x0B": "v", "\x0C": "f", "\x0D": "\\r", '"': '"', "\\": "\\" }; return value.replace(/\x08|[\x0A-\x0D]|"|\\/g, function (value) { return "\\" + replace[value]; }); }; defn = function (name, value) { if (d.createElementNS) { script = d.createElementNS('http://www.w3.org/1999/xhtml', 'script'); } else { script = d.createElement('script'); } script.type = 'text/javascript'; script.appendChild(d.createTextNode(toString(name, value))); d.documentElement.appendChild(script); d.documentElement.removeChild(script); }; } catch (e) { replace = function (value) { var replace = { "\x0A": "\\n", "\x0D": "\\r" }; return value.replace(/"/g, '""').replace(/\n|\r/g, function (value) { return replace[value]; }); }; defn = (this.execScript ? function (name, value) { that.execScript(toString(name, value), 'VBScript'); } : function (name, value) { eval(toString(name, value).substring(6)); }); } defn(name, value); }