<div id="box"> <ul> <li >111 </li> <li class="lione">2222</li> <li class="lione">3333</li> </ul> </div> <div id="box2"> <p>我是AAAA</p> <p>我是BBBB</p> </div>
//選擇器的實現 var element = document.querySelector('selectors'); var elementList = document.querySelectorAll('selectors'); var $=query = document.querySelector.bind(document); var queryAll = document.querySelectorAll.bind(document); //這個是最牛逼的 細細體會就會發現 var fromId = document.getElementById.bind(document); var fromClass = document.getElementsByClassName.bind(document); var fromTag = document.getElementsByTagName.bind(document); //調用 var box=$('#box'); var lioneall=queryAll('li'); var lione=$('.lione'); console.log(box.innerHTML); // console.log(lioneall[2].innerHTML); //333 box.addEventListener('click',function(){ console.log('click lione'+lione.innerHTML); //click lione 2222 });
另外一個不錯的 https://github.com/snandy/zchain/blob/master/%24/selector.jsjavascript
/** * JavaScript Selector * Copyright (c) 2010 snandy * Blog: http://snandy.cnglogs.com * QQ羣: 34580561 * * $ 獲取元素, 在DOM中使用頻繁的,根據2/8原則只實現最經常使用的四種 * * @param {Object} selector * @param {Object} context * * 1, 經過id獲取,該元素是惟一的 * $('#id') * * 2, 經過className獲取 * $('.cls') 獲取文檔中全部className爲cls的元素 * $('.cls', el) * $('.cls', '#id') * $('span.cls') 獲取文檔中全部className爲cls的span元素 * $('span.cls', el) 獲取指定元素中className爲cls的元素, el爲HTMLElement (不推薦) * $('span.cls', '#id') 獲取指定id的元素中className爲cls的元素 * * 3, 經過tagName獲取 * $('span') 獲取文檔中全部的span元素 * $('span', el) 獲取指定元素中的span元素, el爲HTMLElement (不推薦) * $('span', '#id') 獲取指定id的元素中的span元素 * * 4, 經過attribute獲取 * $('[name]') 獲取文檔中具備屬性name的元素 * $('[name]', el) * $('[name]', '#id') * $('[name=uname]') 獲取文檔中全部屬性name=uname的元素 * $('[name=uname]', el) * $('[name=uname]', '#id') * $('input[name=uname]') 獲取文檔中全部屬性name=uname的input元素 * $('input[name=uname]', el) * $('input[name=uname]', '#id') */ ~function(win, doc, undefined) { // Save a reference to core methods var slice = Array.prototype.slice // selector regular expression var rId = /^#[\w\-]+/ var rTag = /^([\w\*]+)$/ var rCls = /^([\w\-]+)?\.([\w\-]+)/ var rAttr = /^([\w]+)?\[([\w]+-?[\w]+?)(=(\w+))?\]/ // For IE9/Firefox/Safari/Chrome/Opera var makeArray = function(obj) { return slice.call(obj, 0) } // For IE6/7/8 try{ slice.call(doc.documentElement.childNodes, 0)[0].nodeType } catch(e) { makeArray = function(obj) { var result = [] for (var i = 0, len = obj.length; i < len; i++) { result[i] = obj[i] } return result } } function byId(id) { return doc.getElementById(id) } function check(attr, val, node) { var reg = RegExp('(?:^|\\s+)' + val + '(?:\\s+|$)') var attribute = attr === 'className' ? node.className : node.getAttribute(attr) if (attribute) { if (val) { if (reg.test(attribute)) return true } else { return true } } return false } function filter(all, attr, val) { var el, result = [] var i = 0, r = 0 while ( (el = all[i++]) ) { if ( check(attr, val, el) ) { result[r++] = el } } return result } function query(selector, context) { var s = selector, arr = [] var context = context === undefined ? doc : typeof context === 'string' ? query(context)[0] : context if (!selector) return arr // id和tagName 直接使用 getElementById 和 getElementsByTagName // id if ( rId.test(s) ) { arr[0] = byId( s.substr(1, s.length) ) return arr } // Tag name if ( rTag.test(s) ) { return makeArray(context.getElementsByTagName(s)) } // 優先使用querySelector,現代瀏覽器都實現它了 if (context.querySelectorAll) { if (context.nodeType === 1) { var old = context.id, id = context.id = '__ZZ__' try { return context.querySelectorAll('#' + id + ' ' + s) } catch(e) { throw new Error('querySelectorAll: ' + e) } finally { old ? context.id = old : context.removeAttribute('id') } } return makeArray(context.querySelectorAll(s)) } // ClassName if ( rCls.test(s) ) { var ary = s.split('.') var tag = ary[0] var cls = ary[1] if (context.getElementsByClassName) { var elems = context.getElementsByClassName(cls) if (tag) { for (var i = 0, len = elems.length; i < len; i++) { var el = elems[i] el.tagName.toLowerCase() === tag && arr.push(el) } return arr } else { return makeArray(elems) } } else { var all = context.getElementsByTagName(tag || '*') return filter(all, 'className', cls) } } // Attribute if ( rAttr.test(s) ) { var result = rAttr.exec(s) var all = context.getElementsByTagName(result[1] || '*') return filter(all, result[2], result[4]) } } win.query = win.$ = query }(this, document);
var myOffest=function (obj){ var top=0,left=0; if(obj){ while(obj.offsetParent){ top += obj.offsetTop; left += obj.offsetLeft; obj = obj.offsetParent; } } return{ top : top, left : left } }
var jqtop=jQuery('#box2').offset().top; console.log('jQuery offsetTop 值'+jqtop); // jQuery offsetTop 值274 var jstop=document.getElementById("box2"); console.log('js offsetTop 值'+myOffest(jstop).top); // js offsetTop 值274
var unboundForEach = Array.prototype.forEach,forEach = Function.prototype.call.bind(unboundForEach);
<div id="box3"> <p class="klasses">one</p> <p class="klasses">two</p> <p class="klasses">three</p> </div> <script> var unboundForEach = Array.prototype.forEach,forEach = Function.prototype.call.bind(unboundForEach); var box3=document.getElementById("box3"); var klasses=document.querySelectorAll('.klasses') forEach(klasses, function (el) { el.addEventListener('click', function(){ alert('點擊個人序號'+this.innerHTML); //點擊個人序號 one }); }); </script>
function jQueryEach(object, callback, args) { var name, i = 0, length = object.length; if (args) { if (length == undefined) { for (name in object) { if (callback.apply(object[name], args) === false) { break } } } else { for (; i < length;) { if (callback.apply(object[i++], args) === false) { break } } } } else { if (length == undefined) { for (name in object) { if (callback.call(object[name], name, object[name]) === false) { break } } } else { for (var value = object[0]; i < length && callback.call(value, i, value) !== false; value = object[++i]) {} } } return object };
var arr1 = [ "one", "two", "three", "four", "five" ]; jQueryEach(arr1, function(index){ console.log(arr1[index]); // alert(this) }); var obj = { one:'張珊', two:'李四', three:3, four:4, five:'王五' }; jQueryEach(obj, function(key, val) { console.log('val'+obj[key]); });
Array.prototype.forEach2=function(fun,context){ var len=this.length; var context=arguments[1]; //即便爲undefined,call函數也正常運行。 if(typeof fun !=="function"){ throw "輸入正確函數!"; } for(var i=0;i<len;i++){ fun.apply(context,[i,this[i],this]); //fun.call(context,i,this[i],this); } }; var arr2=[5,6,7]; //arr.forEach2(function(item,index,arr){ //console.log(item,index,arr); //});
<!doctype html> <html> <head> <meta charset="utf-8"> <title>無標題文檔</title> </head> <body> 運行如下代碼,正好就是jquery的hover方法 <div id="dd" style="width:100px; height:100px; border:1px solid #3d3d3d; position:relative;"> <div id="dd2" style="width:50px; height:50px; overflow:hidden; background-color:#cccccc; position:absolute; left:30px; top:30px;"></div> </div> <script language="javascript"> function bind(elem,ev,callback) { if(document.all) { elem.attachEvent("on"+ev,callback); }else{ elem.addEventListener(ev,callback,false); } } function unbind(elem,ev,callback) { if(typeof(callback)=="function") { if(document.all) { elem.detachEvent("on"+ev,callback); }else{ elem.removeEventListener(ev,callback,false); } }else{ if(document.all) { elem.detachEvent("on"+ev); }else{ elem.removeEventListener(ev,false); } } } function hover(elem,overCallback,outCallback){//實現hover事件 var isHover=false;//判斷是否懸浮在上方 var preOvTime=new Date().getTime();//上次懸浮時間 function over(e){ var curOvTime=new Date().getTime(); isHover=true;//處於over狀態 if(curOvTime-preOvTime>10) {//時間間隔超過10毫秒,認爲鼠標完成了mouseout事件 overCallback(e,elem); } preOvTime=curOvTime; } function out(e) { var curOvTime=new Date().getTime(); preOvTime=curOvTime; isHover=false; setTimeout(function(){ if(!isHover) { outCallback(e,elem); } },10); } bind(elem,"mouseover",over); bind(elem,"mouseout",out); }; hover(document.getElementById("dd"), function(){console.log("進來1"); document.getElementById("dd2").innerHTML="進來了";}, function(){ console.log("出來2"); document.getElementById("dd2").innerHTML="出來了"; } ); </script> </body> </html>
//獲取文檔完整的高度 var getScrollHeight=function () { return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); } console.log('jquery文檔高度'+jQuery(document).height()); //jquery文檔高度1739 console.log('js文檔高度'+getScrollHeight()); // js文檔高度1739
// jQuery $('.el').addClass('class'); $('.el').removeClass('class'); $('.el').toggleClass('class'); // 原生方法 document.querySelector('.el').classList.add('class'); document.querySelector('.el').classList.remove('class'); document.querySelector('.el').classList.toggle('class'); // 原生方法 擴展添加多個 DOMTokenList.prototype.adds = function(tokens) { tokens.split(" ").forEach(function(token) { this.add(token); }.bind(this)); return this; }; // adds 添加多個 document.querySelector(".el").classList.adds("child1 child2 child3");
function hasClass(ele, cls) { return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); } function addClass(ele, cls) { if (!this.hasClass(ele, cls)) ele.className += " " + cls; } function removeClass(ele, cls) { if (hasClass(ele, cls)) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); ele.className = ele.className.replace(reg, ' '); } }
function getJSONP2(url,success,jsonpCallback,jsonp){ var jsonp=jsonp||"callback", cn=jsonpCallback||"jsonpCallback", url=url.toString(), dataString = url.indexOf('?') == -1? '?': '&', s=document.createElement("script"), head=document.head||document.getElementsByTagName("head")[0]; s.type="text/javascript"; s.charset="UTF-8";s.src=url+dataString+"_="+(+new Date)+"&"+jsonp+"="+cn; head.insertBefore(s,head.firstChild); console.log("src",s.src); setTimeout(function(){ window[cn]=function(data){ try{s.onload=s.onreadystatechange=function(){ var that=this; if((!that.readyState||that.readyState==="loaded"||that.readyState==="complete")){ success&&success(data); s.onload=s.onreadystatechange=null;if(head&&s.parentNode){ head.removeChild(s)}}}}catch(e){}finally{window[cn]=null}} },0)};
var url44="http://api.map.baidu.com/geocoder/v2/?sa=1&location=30.290466116991468,120.00192773949404&output=json&pois=1&latest_admin=1&ak=ABq5yEuwLp5Z4yWlRDGX3vEhxxjGDu8L"; getJSONP2(url44,function(data){ var data=data; data.regeocode=data.result; //var address = data.regeocode.formatted_address; console.log(data,"結果" , data.regeocode.formatted_address); })
//document.addEventListener('click',function(){ getJSONP("https://api.github.com/repos/HubSpot/pace?callback=",function(json){ alert('success!'+ json.data.id+'獲取到的'+json.data.name); document.getElementById("testText").innerHTML='回調函數獲取到了'+json.data.name; document.getElementById("testText").style.cssText='color:red;font-size:22px; border:1px solid #666' });
function trimStr(str){return str.replace(/(^\s*)|(\s*$)/g,"");} function TrimAll(str,is_global){ //刪除所有空格 var result; result = str.replace(/(^\s+)|(\s+$)/g,""); if(is_global.toLowerCase()=="g") { result = result.replace(/\s/g,""); } return result; }
tring.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); }; String.prototype.ltrim = function() { return this.replace(/(^\s*)/g, ""); }; String.prototype.rtrim = function() { return this.replace(/(\s*$)/g, ""); }; String.prototype.trimAll = function () { return this.replace(/\s+/g, ""); }
function addCookie(objName,objValue,objHours){ var str = objName + "=" + escape(objValue); if(objHours > 0){ var date = new Date(); var ms = objHours*3600*1000; date.setTime(date.getTime() + ms); str += "; expires=" + date.toGMTString(); } str += "; path=/"; document.cookie = str; }; function getCookie (objName){ var arrStr = document.cookie.split("; "); for(var i = 0;i < arrStr.length;i ++){ var temp = arrStr[i].split("="); if(temp[0] == objName) return unescape(temp[1]); } };
/** * ajax封裝 * var xmlhttp = new YAjax(); * xmlhttp.request({ * url : "./demo.php", // get請求時 能夠這樣寫 "./demo.php?name=zhangsan" * method : "POST", * data : "name=李四", // 支持json傳值 {"name":"zhangsan"} get時不用該參數 * receiveType : "html", // json html or xml * timeout : 3000, // 3秒 async : true, //默認true 可省略 * beforeSend:function(){}, //請求以前回調函數 就得 這邊beforesent s小寫 beforesend * success : function(d) {alert(d);}, * error : function(xmlhttp){alert('timeout');} * }); */
function YAjax() { this._self = this; this.xmlhttp = this.init() } YAjax.prototype = { constructor: YAjax, init: function() { var xmlhttp = null; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); if (xmlhttp.overrideMimeType) { xmlhttp.overrideMimeType("text/xml") } } else { if (window.ActiveXObject) { var activexName = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < activexName.length; i++) { try { xmlhttp = new ActiveXObject(activexName[i]); break } catch(e) {} } } } return xmlhttp }, extend: function(destination, source, override) { if (undefined == override) { override = true } if (typeof destination != "object" && typeof destination != "function") { if (!override) { return destination } else { destination = {} } } var property = ""; for (property in source) { if (override || !(property in destination)) { destination[property] = source[property] } } return destination }, json2String: function(jsonData) { var strArr = []; for (var k in jsonData) { strArr.push(k + "=" + jsonData[k]) } return strArr.join("&") }, request: function(opt) { var _self = this, isTimeout = false, timeFlag = 0, options = { url: "", data: "", method: "POST", receiveType: "html", timeout: 7000, async: opt.async || true, beforeSend: function() {}, success: function() { alert("define your success function") }, error: function(xmlhttp) {} }; if ("data" in opt) { if (typeof opt.data == "string") {} else { opt.data = this.json2String(opt.data) } } options = this.extend(options, opt); this.xmlhttp.onreadystatechange = function() { if (_self.xmlhttp.readyState == 2) { options.beforeSend && options.beforeSend.apply(_self.xmlhttp, arguments) } if (_self.xmlhttp.readyState == 4) { if (!isTimeout && _self.xmlhttp.status == 200) { clearTimeout(timeFlag); var t = options.receiveType.toLowerCase(); if (t == "html") { options.success(_self.xmlhttp.responseText) } else { if (t == "xml") { options.success(_self.xmlhttp.responseXML) } else { if (t == "json") { try { var obj = JSON.parse(_self.xmlhttp.responseText); options.success(obj) } catch(e) { var str = "(" + _self.xmlhttp.responseText + ")"; options.success(JSON.parse(str)) } } else {} } } } else { clearTimeout(timeFlag); options.error(_self.xmlhttp) } } }; clearTimeout(timeFlag); timeFlag = setTimeout(function() { if (_self.xmlhttp.readyState != 4) { isTimeout = true; _self.xmlhttp.abort(); clearTimeout(timeFlag) } }, options.timeout); this.xmlhttp.open(options.method.toUpperCase(), options.url, options.async); if (options.method.toUpperCase() == "POST") { this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); this.xmlhttp.send(options.data) } else { this.xmlhttp.send(null) } } };
/*! echo.js v1.7.0 | (c) 2015 @toddmotto | https://github.com/toddmotto/echo */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(function() { return factory(root); }); } else if (typeof exports === 'object') { module.exports = factory; } else { root.echo = factory(root); } })(this, function (root) { 'use strict'; var echo = {}; var callback = function () {}; var offset, poll, delay, useDebounce, unload,effectClass; var classList= 'classList' in document.documentElement ?1:0; var isHidden = function (element) { return (element.offsetParent === null); }; var inView = function (element, view) { if (isHidden(element)) { return false; } var box = element.getBoundingClientRect(); return (box.right >= view.l && box.bottom >= view.t && box.left <= view.r && box.top <= view.b); }; var debounceOrThrottle = function () { if(!useDebounce && !!poll) { return; } clearTimeout(poll); poll = setTimeout(function(){ echo.render(); poll = null; }, delay); }; echo.init = function (opts) { opts = opts || {}; var offsetAll = opts.offset || 0; var offsetVertical = opts.offsetVertical || offsetAll; var offsetHorizontal = opts.offsetHorizontal || offsetAll; var optionToInt = function (opt, fallback) { return parseInt(opt || fallback, 10); }; offset = { t: optionToInt(opts.offsetTop, offsetVertical), b: optionToInt(opts.offsetBottom, offsetVertical), l: optionToInt(opts.offsetLeft, offsetHorizontal), r: optionToInt(opts.offsetRight, offsetHorizontal) }; delay = optionToInt(opts.throttle, 80); useDebounce = opts.debounce !== false; effectClass=opts.effectClass; unload = !!opts.unload; callback = opts.callback || callback; echo.render(); if (document.addEventListener) { root.addEventListener('scroll', debounceOrThrottle, false); root.addEventListener('load', debounceOrThrottle, false); } else { root.attachEvent('onscroll', debounceOrThrottle); root.attachEvent('onload', debounceOrThrottle); } }; echo.render = function () { var nodes = document.querySelectorAll('img[data-echo], [data-echo-background]'); var length = nodes.length; var src, elem; var view = { l: 0 - offset.l, t: 0 - offset.t, b: (root.innerHeight || document.documentElement.clientHeight) + offset.b, r: (root.innerWidth || document.documentElement.clientWidth) + offset.r }; for (var i = 0; i < length; i++) { elem = nodes[i]; if (inView(elem, view)) { if (unload) { elem.setAttribute('data-echo-placeholder', elem.src); } if (elem.getAttribute('data-echo-background') !== null) { elem.style.backgroundImage = "url(" + elem.getAttribute('data-echo-background') + ")"; } else { elem.src = elem.getAttribute('data-echo'); } if (!unload) { if(effectClass){ if (classList){ elem.classList.add(effectClass); }else{ elem.className += " " + effectClass; } } elem.removeAttribute('data-echo'); elem.removeAttribute('data-echo-background'); } callback(elem, 'load'); } else if (unload && !!(src = elem.getAttribute('data-echo-placeholder'))) { if (elem.getAttribute('data-echo-background') !== null) { elem.style.backgroundImage = "url(" + src + ")"; } else { elem.src = src; } elem.removeAttribute('data-echo-placeholder'); callback(elem, 'unload'); } } if (!length) { echo.detach(); } }; echo.detach = function () { if (document.removeEventListener) { root.removeEventListener('scroll', debounceOrThrottle); } else { root.detachEvent('onscroll', debounceOrThrottle); } clearTimeout(poll); }; return echo; });
使用方法php
<img src="img/blank.gif" alt="Photo" data-echo="img/photo.jpg"> <script src="../echo.js"></script> <script> echo.init({ offset: 100, throttle: 250, unload: false, callback: function (element, op) { console.log(element, 'has been', op + 'ed') } });
function Domready(readyFn) { if (document.addEventListener) { document.addEventListener("DOMContentLoaded", function() { readyFn && readyFn() }, false) } else { var bReady = false; document.attachEvent("onreadystatechange", function() { if (bReady) { return } if (document.readyState == "complete" || document.readyState == "interactive") { bReady = true; readyFn && readyFn() } }); setTimeout(checkDoScroll, 1) } function checkDoScroll() { try { document.documentElement.doScroll("left"); if (bReady) { return } bReady = true; readyFn && readyFn() } catch (e) { setTimeout(checkDoScroll, 1) } } };
Element.prototype.on = Element.prototype.addEventListener;
HTMLElement.prototype.trigger = function (type, data) { var event = document.createEvent('HTMLEvents'); event.initEvent(type, true, true); event.data = data || {}; event.eventName = type; event.target = this; this.dispatchEvent(event); return this; };
//獲取文檔完整的高度 var getScrollHeight=function () { return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); }
//獲取當前但是範圍的高度 var getClientHeight=function () { var clientHeight = 0; if (document.body.clientHeight && document.documentElement.clientHeight) { clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight); } else { clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight); } return clientHeight; }
。。。。剩下的慢慢添加...css