原生选择器   充分利用 bind(this)绑定

  1. <div id="box">
  2. <ul>
  3. <li >111 </li>
  4. <li class="lione">2222</li>
  5. <li class="lione">3333</li>
  6. </ul>
  7.  
  8. </div>
  9.  
  10. <div id="box2">
  11. <p>我是AAAA</p>
  12. <p>我是BBBB</p>
  13. </div>

  

  1. //选择器的实现
  2. var element = document.querySelector('selectors');
  3. var elementList = document.querySelectorAll('selectors');
  4.  
  5. var $=query = document.querySelector.bind(document);
  6. var queryAll = document.querySelectorAll.bind(document); //这个是最牛逼的 细细体会就会发现
  7. var fromId = document.getElementById.bind(document);
  8. var fromClass = document.getElementsByClassName.bind(document);
  9. var fromTag = document.getElementsByTagName.bind(document);
  10.  
  11. //调用
  12. var box=$('#box');
  13. var lioneall=queryAll('li');
  14. var lione=$('.lione');
  15. console.log(box.innerHTML); //
  16. console.log(lioneall[2].innerHTML); //333
  17.  
  18. box.addEventListener('click',function(){
  19. console.log('click lione'+lione.innerHTML); //click lione 2222
  20. });

 另一个不错的  https://github.com/snandy/zchain/blob/master/%24/selector.js

  1. /**
  2. * JavaScript Selector
  3. * Copyright (c) 2010 snandy
  4. * Blog: http://snandy.cnglogs.com
  5. * QQ群: 34580561
  6. *
  7. * $ 获取元素, 在DOM中使用频繁的,根据2/8原则只实现最常用的四种
  8. *
  9. * @param {Object} selector
  10. * @param {Object} context
  11. *
  12. * 1, 通过id获取,该元素是唯一的
  13. * $('#id')
  14. *
  15. * 2, 通过className获取
  16. * $('.cls') 获取文档中所有className为cls的元素
  17. * $('.cls', el)
  18. * $('.cls', '#id')
  19. * $('span.cls') 获取文档中所有className为cls的span元素
  20. * $('span.cls', el) 获取指定元素中className为cls的元素, el为HTMLElement (不推荐)
  21. * $('span.cls', '#id') 获取指定id的元素中className为cls的元素
  22. *
  23. * 3, 通过tagName获取
  24. * $('span') 获取文档中所有的span元素
  25. * $('span', el) 获取指定元素中的span元素, el为HTMLElement (不推荐)
  26. * $('span', '#id') 获取指定id的元素中的span元素
  27. *
  28. * 4, 通过attribute获取
  29. * $('[name]') 获取文档中具有属性name的元素
  30. * $('[name]', el)
  31. * $('[name]', '#id')
  32. * $('[name=uname]') 获取文档中所有属性name=uname的元素
  33. * $('[name=uname]', el)
  34. * $('[name=uname]', '#id')
  35. * $('input[name=uname]') 获取文档中所有属性name=uname的input元素
  36. * $('input[name=uname]', el)
  37. * $('input[name=uname]', '#id')
  38. */
  39. ~function(win, doc, undefined) {
  40.  
  41. // Save a reference to core methods
  42. var slice = Array.prototype.slice
  43.  
  44. // selector regular expression
  45. var rId = /^#[\w\-]+/
  46. var rTag = /^([\w\*]+)$/
  47. var rCls = /^([\w\-]+)?\.([\w\-]+)/
  48. var rAttr = /^([\w]+)?\[([\w]+-?[\w]+?)(=(\w+))?\]/
  49.  
  50. // For IE9/Firefox/Safari/Chrome/Opera
  51. var makeArray = function(obj) {
  52. return slice.call(obj, 0)
  53. }
  54. // For IE6/7/8
  55. try{
  56. slice.call(doc.documentElement.childNodes, 0)[0].nodeType
  57. } catch(e) {
  58. makeArray = function(obj) {
  59. var result = []
  60. for (var i = 0, len = obj.length; i < len; i++) {
  61. result[i] = obj[i]
  62. }
  63. return result
  64. }
  65. }
  66.  
  67. function byId(id) {
  68. return doc.getElementById(id)
  69. }
  70. function check(attr, val, node) {
  71. var reg = RegExp('(?:^|\\s+)' + val + '(?:\\s+|$)')
  72. var attribute = attr === 'className'
  73. ? node.className
  74. : node.getAttribute(attr)
  75. if (attribute) {
  76. if (val) {
  77. if (reg.test(attribute)) return true
  78. } else {
  79. return true
  80. }
  81. }
  82. return false
  83. }
  84. function filter(all, attr, val) {
  85. var el, result = []
  86. var i = 0, r = 0
  87. while ( (el = all[i++]) ) {
  88. if ( check(attr, val, el) ) {
  89. result[r++] = el
  90. }
  91. }
  92. return result
  93. }
  94.  
  95. function query(selector, context) {
  96. var s = selector, arr = []
  97. var context = context === undefined
  98. ? doc
  99. : typeof context === 'string' ? query(context)[0] : context
  100.  
  101. if (!selector) return arr
  102.  
  103. // id和tagName 直接使用 getElementById 和 getElementsByTagName
  104.  
  105. // id
  106. if ( rId.test(s) ) {
  107. arr[0] = byId( s.substr(1, s.length) )
  108. return arr
  109. }
  110.  
  111. // Tag name
  112. if ( rTag.test(s) ) {
  113. return makeArray(context.getElementsByTagName(s))
  114. }
  115.  
  116. // 优先使用querySelector,现代浏览器都实现它了
  117. if (context.querySelectorAll) {
  118. if (context.nodeType === 1) {
  119. var old = context.id, id = context.id = '__ZZ__'
  120. try {
  121. return context.querySelectorAll('#' + id + ' ' + s)
  122. } catch(e) {
  123. throw new Error('querySelectorAll: ' + e)
  124. } finally {
  125. old ? context.id = old : context.removeAttribute('id')
  126. }
  127. }
  128. return makeArray(context.querySelectorAll(s))
  129. }
  130.  
  131. // ClassName
  132. if ( rCls.test(s) ) {
  133. var ary = s.split('.')
  134. var tag = ary[0]
  135. var cls = ary[1]
  136. if (context.getElementsByClassName) {
  137. var elems = context.getElementsByClassName(cls)
  138. if (tag) {
  139. for (var i = 0, len = elems.length; i < len; i++) {
  140. var el = elems[i]
  141. el.tagName.toLowerCase() === tag && arr.push(el)
  142. }
  143. return arr
  144. } else {
  145. return makeArray(elems)
  146. }
  147. } else {
  148. var all = context.getElementsByTagName(tag || '*')
  149. return filter(all, 'className', cls)
  150. }
  151. }
  152.  
  153. // Attribute
  154. if ( rAttr.test(s) ) {
  155. var result = rAttr.exec(s)
  156. var all = context.getElementsByTagName(result[1] || '*')
  157. return filter(all, result[2], result[4])
  158. }
  159. }
  160.  
  161. win.query = win.$ = query
  162. }(this, document);

  

原生js实现jQuery的offset函数

  1. var myOffest=function (obj){
  2. var top=0,left=0;
  3. if(obj){
  4. while(obj.offsetParent){
  5. top += obj.offsetTop;
  6. left += obj.offsetLeft;
  7. obj = obj.offsetParent;
  8. }
  9. }
  10.  
  11. return{
  12. top : top,
  13. left : left
  14. }
  15. }

  

  1. var jqtop=jQuery('#box2').offset().top;
  2. console.log('jQuery offsetTop 值'+jqtop); // jQuery offsetTop 值274
  3.  
  4. var jstop=document.getElementById("box2");
  5. console.log('js offsetTop 值'+myOffest(jstop).top); // js offsetTop 值274

 

利用数组 forEach的实现

  1. var unboundForEach = Array.prototype.forEach,forEach = Function.prototype.call.bind(unboundForEach);
  1. <div id="box3">
  2. <p class="klasses">one</p>
  3. <p class="klasses">two</p>
  4. <p class="klasses">three</p>
  5. </div>
  6.  
  7. <script>
  8. var unboundForEach = Array.prototype.forEach,forEach = Function.prototype.call.bind(unboundForEach);
  9.  
  10. var box3=document.getElementById("box3");
  11. var klasses=document.querySelectorAll('.klasses')
  12. forEach(klasses, function (el) {
  13. el.addEventListener('click', function(){
  14. alert('点击我的序号'+this.innerHTML); //点击我的序号 one
  15. });
  16. });
  17.  
  18. </script>

jquery的静态方法 $.each

  1. function jQueryEach(object, callback, args) {
  2. var name,
  3. i = 0,
  4. length = object.length;
  5. if (args) {
  6. if (length == undefined) {
  7. for (name in object) {
  8. if (callback.apply(object[name], args) === false) {
  9. break
  10. }
  11. }
  12. } else {
  13. for (; i < length;) {
  14. if (callback.apply(object[i++], args) === false) {
  15. break
  16. }
  17. }
  18. }
  19. } else {
  20. if (length == undefined) {
  21. for (name in object) {
  22. if (callback.call(object[name], name, object[name]) === false) {
  23. break
  24. }
  25. }
  26. } else {
  27. for (var value = object[0]; i < length && callback.call(value, i, value) !== false; value = object[++i]) {}
  28. }
  29. }
  30. return object
  31. };

 

  1. var arr1 = [ "one", "two", "three", "four", "five" ];
  2. jQueryEach(arr1, function(index){
  3. console.log(arr1[index]);
  4. // alert(this)
  5. });
  6.  
  7. var obj = { one:'张珊', two:'李四', three:3, four:4, five:'王五' };
  8. jQueryEach(obj, function(key, val) {
  9. console.log('val'+obj[key]);
  10. });

  

 

  1. Array.prototype.forEach2=function(fun,context){
  2. var len=this.length;
  3. var context=arguments[1]; //即使为undefined,call函数也正常运行。
  4. if(typeof fun !=="function"){
  5. throw "输入正确函数!";
  6. }
  7. for(var i=0;i<len;i++){
  8. fun.apply(context,[i,this[i],this]);
  9. //fun.call(context,i,this[i],this);
  10. }
  11. };
  12. var arr2=[5,6,7];
  13. //arr.forEach2(function(item,index,arr){
  14. //console.log(item,index,arr);
  15. //});

hover 方法

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>无标题文档</title>
  6. </head>
  7.  
  8. <body>
  9.  
  10. 运行以下代码,正好就是jquery的hover方法
  11. <div id="dd" style="width:100px; height:100px; border:1px solid #3d3d3d; position:relative;">
  12. <div id="dd2" style="width:50px; height:50px; overflow:hidden; background-color:#cccccc; position:absolute; left:30px; top:30px;"></div>
  13. </div>
  14.  
  15. <script language="javascript">
  16.  
  17. function bind(elem,ev,callback)
  18. {
  19. if(document.all)
  20. {
  21. elem.attachEvent("on"+ev,callback);
  22. }else{
  23. elem.addEventListener(ev,callback,false);
  24. }
  25. }
  26. function unbind(elem,ev,callback)
  27. {
  28. if(typeof(callback)=="function")
  29. {
  30. if(document.all)
  31. {
  32. elem.detachEvent("on"+ev,callback);
  33. }else{
  34. elem.removeEventListener(ev,callback,false);
  35. }
  36. }else{
  37. if(document.all)
  38. {
  39. elem.detachEvent("on"+ev);
  40. }else{
  41. elem.removeEventListener(ev,false);
  42. }
  43. }
  44. }
  45. function hover(elem,overCallback,outCallback){//实现hover事件
  46. var isHover=false;//判断是否悬浮在上方
  47. var preOvTime=new Date().getTime();//上次悬浮时间
  48.  
  49. function over(e){
  50. var curOvTime=new Date().getTime();
  51. isHover=true;//处于over状态
  52. if(curOvTime-preOvTime>10)
  53. {//时间间隔超过10毫秒,认为鼠标完成了mouseout事件
  54. overCallback(e,elem);
  55. }
  56. preOvTime=curOvTime;
  57. }
  58.  
  59. function out(e)
  60. {
  61. var curOvTime=new Date().getTime();
  62. preOvTime=curOvTime;
  63. isHover=false;
  64. setTimeout(function(){
  65. if(!isHover)
  66. {
  67. outCallback(e,elem);
  68. }
  69. },10);
  70. }
  71. bind(elem,"mouseover",over);
  72. bind(elem,"mouseout",out);
  73. };
  74.  
  75. hover(document.getElementById("dd"),
  76. function(){console.log("进来1"); document.getElementById("dd2").innerHTML="进来了";},
  77. function(){ console.log("出来2"); document.getElementById("dd2").innerHTML="出来了"; }
  78. );
  79.  
  80. </script>
  81.  
  82. </body>
  83. </html>

  

  

获取文档高度

  1. //获取文档完整的高度
  2. var getScrollHeight=function () {
  3. return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
  4. }
  5.  
  6. console.log('jquery文档高度'+jQuery(document).height()); //jquery文档高度1739
  7. console.log('js文档高度'+getScrollHeight()); // js文档高度1739

 样式操作 

  1. // jQuery
  2. $('.el').addClass('class');
  3. $('.el').removeClass('class');
  4. $('.el').toggleClass('class');
  5.  
  6. // 原生方法
  7. document.querySelector('.el').classList.add('class');
  8. document.querySelector('.el').classList.remove('class');
  9. document.querySelector('.el').classList.toggle('class');
  10.  
  11. // 原生方法 扩展添加多个
  12. DOMTokenList.prototype.adds = function(tokens) {
  13. tokens.split(" ").forEach(function(token) {
  14. this.add(token);
  15. }.bind(this));
  16. return this;
  17. };
  18.  
  19. // adds 添加多个
  20. document.querySelector(".el").classList.adds("child1 child2 child3");
  1. function hasClass(ele, cls) {
  2. return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  3. }
  4. function addClass(ele, cls) {
  5. if (!this.hasClass(ele, cls)) ele.className += " " + cls;
  6. }
  7. function removeClass(ele, cls) {
  8. if (hasClass(ele, cls)) {
  9. var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
  10. ele.className = ele.className.replace(reg, ' ');
  11. }
  12. }

获取jsonp

  1. function getJSONP2(url,success,jsonpCallback,jsonp){
  2. var jsonp=jsonp||"callback",
  3. cn=jsonpCallback||"jsonpCallback",
  4. url=url.toString(),
  5. dataString = url.indexOf('?') == -1? '?': '&',
  6. s=document.createElement("script"),
  7. head=document.head||document.getElementsByTagName("head")[0];
  8. s.type="text/javascript";
  9. s.charset="UTF-8";s.src=url+dataString+"_="+(+new Date)+"&"+jsonp+"="+cn;
  10.  
  11. head.insertBefore(s,head.firstChild);
  12. console.log("src",s.src);
  13. setTimeout(function(){
  14. window[cn]=function(data){
  15.  
  16. try{s.onload=s.onreadystatechange=function(){
  17. var that=this;
  18. if((!that.readyState||that.readyState==="loaded"||that.readyState==="complete")){
  19. success&&success(data);
  20. s.onload=s.onreadystatechange=null;if(head&&s.parentNode){
  21. head.removeChild(s)}}}}catch(e){}finally{window[cn]=null}}
  22. },0)};
  1. 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";
  2. getJSONP2(url44,function(data){
  3. var data=data;
  4. data.regeocode=data.result;
  5. //var address = data.regeocode.formatted_address;
  6.  
  7. console.log(data,"结果" , data.regeocode.formatted_address);
  8.  
  9. })
  1.  
  2. //document.addEventListener('click',function(){
  3. getJSONP("https://api.github.com/repos/HubSpot/pace?callback=",function(json){
  4. alert('success!'+ json.data.id+'获取到的'+json.data.name);
  5. document.getElementById("testText").innerHTML='回调函数获取到了'+json.data.name;
  6. document.getElementById("testText").style.cssText='color:red;font-size:22px; border:1px solid #666'
  7. });

清楚字符串空格

  1. function trimStr(str){return str.replace(/(^\s*)|(\s*$)/g,"");}
  2.  
  3. function TrimAll(str,is_global){ //删除全部空格
  4. var result;
  5. result = str.replace(/(^\s+)|(\s+$)/g,"");
  6. if(is_global.toLowerCase()=="g")
  7. {
  8. result = result.replace(/\s/g,"");
  9. }
  10. return result;
  11. }
  1. tring.prototype.trim = function() {
  2. return this.replace(/(^\s*)|(\s*$)/g, "");
  3. };
  4. String.prototype.ltrim = function() {
  5. return this.replace(/(^\s*)/g, "");
  6. };
  7. String.prototype.rtrim = function() {
  8. return this.replace(/(\s*$)/g, "");
  9. };
  10. String.prototype.trimAll = function () {
  11. return this.replace(/\s+/g, "");
  12. }

  

 cookie的操作

  1. function addCookie(objName,objValue,objHours){
  2. var str = objName + "=" + escape(objValue);
  3. if(objHours > 0){
  4. var date = new Date();
  5. var ms = objHours*3600*1000;
  6. date.setTime(date.getTime() + ms);
  7. str += "; expires=" + date.toGMTString();
  8. }
  9. str += "; path=/";
  10. document.cookie = str;
  11.  
  12. };
  13.  
  14. function getCookie (objName){
  15. var arrStr = document.cookie.split("; ");
  16. for(var i = 0;i < arrStr.length;i ++){
  17. var temp = arrStr[i].split("=");
  18. if(temp[0] == objName) return unescape(temp[1]);
  19. }
  20. };

原生ajax的操作

  1. /**
  2. * ajax封装
  3. * var xmlhttp = new YAjax();
  4. * xmlhttp.request({
  5. * url : "./demo.php", // get请求时 可以这样写 "./demo.php?name=zhangsan"
  6. * method : "POST",
  7. * data : "name=李四", // 支持json传值 {"name":"zhangsan"} get时不用该参数
  8. * receiveType : "html", // json html or xml
  9. * timeout : 3000, // 3秒
  10. async : true, //默认true 可省略
  11. * beforeSend:function(){}, //请求之前回调函数 就得 这边beforesent s小写 beforesend
  12. * success : function(d) {alert(d);},
  13. * error : function(xmlhttp){alert('timeout');}
  14. * });
  15. */

  

  1. function YAjax() {
  2. this._self = this;
  3. this.xmlhttp = this.init()
  4. }
  5. YAjax.prototype = {
  6. constructor: YAjax,
  7. init: function() {
  8. var xmlhttp = null;
  9. if (window.XMLHttpRequest) {
  10. xmlhttp = new XMLHttpRequest();
  11. if (xmlhttp.overrideMimeType) {
  12. xmlhttp.overrideMimeType("text/xml")
  13. }
  14. } else {
  15. if (window.ActiveXObject) {
  16. var activexName = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
  17. for (var i = 0; i < activexName.length; i++) {
  18. try {
  19. xmlhttp = new ActiveXObject(activexName[i]);
  20. break
  21. } catch(e) {}
  22. }
  23. }
  24. }
  25. return xmlhttp
  26. },
  27. extend: function(destination, source, override) {
  28. if (undefined == override) {
  29. override = true
  30. }
  31. if (typeof destination != "object" && typeof destination != "function") {
  32. if (!override) {
  33. return destination
  34. } else {
  35. destination = {}
  36. }
  37. }
  38. var property = "";
  39. for (property in source) {
  40. if (override || !(property in destination)) {
  41. destination[property] = source[property]
  42. }
  43. }
  44. return destination
  45. },
  46. json2String: function(jsonData) {
  47. var strArr = [];
  48. for (var k in jsonData) {
  49. strArr.push(k + "=" + jsonData[k])
  50. }
  51. return strArr.join("&")
  52. },
  53. request: function(opt) {
  54. var _self = this,
  55. isTimeout = false,
  56. timeFlag = 0,
  57. options = {
  58. url: "",
  59. data: "",
  60. method: "POST",
  61. receiveType: "html",
  62. timeout: 7000,
  63. async: opt.async || true,
  64. beforeSend: function() {},
  65. success: function() {
  66. alert("define your success function")
  67. },
  68. error: function(xmlhttp) {}
  69. };
  70. if ("data" in opt) {
  71. if (typeof opt.data == "string") {} else {
  72. opt.data = this.json2String(opt.data)
  73. }
  74. }
  75. options = this.extend(options, opt);
  76. this.xmlhttp.onreadystatechange = function() {
  77. if (_self.xmlhttp.readyState == 2) {
  78. options.beforeSend && options.beforeSend.apply(_self.xmlhttp, arguments)
  79. }
  80. if (_self.xmlhttp.readyState == 4) {
  81. if (!isTimeout && _self.xmlhttp.status == 200) {
  82. clearTimeout(timeFlag);
  83. var t = options.receiveType.toLowerCase();
  84. if (t == "html") {
  85. options.success(_self.xmlhttp.responseText)
  86. } else {
  87. if (t == "xml") {
  88. options.success(_self.xmlhttp.responseXML)
  89. } else {
  90. if (t == "json") {
  91. try {
  92. var obj = JSON.parse(_self.xmlhttp.responseText);
  93. options.success(obj)
  94. } catch(e) {
  95. var str = "(" + _self.xmlhttp.responseText + ")";
  96. options.success(JSON.parse(str))
  97. }
  98. } else {}
  99. }
  100. }
  101. } else {
  102. clearTimeout(timeFlag);
  103. options.error(_self.xmlhttp)
  104. }
  105. }
  106. };
  107. clearTimeout(timeFlag);
  108. timeFlag = setTimeout(function() {
  109. if (_self.xmlhttp.readyState != 4) {
  110. isTimeout = true;
  111. _self.xmlhttp.abort();
  112. clearTimeout(timeFlag)
  113. }
  114. },
  115. options.timeout);
  116. this.xmlhttp.open(options.method.toUpperCase(), options.url, options.async);
  117. if (options.method.toUpperCase() == "POST") {
  118. this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  119. this.xmlhttp.send(options.data)
  120. } else {
  121. this.xmlhttp.send(null)
  122. }
  123. }
  124. };

原生延迟加载插件

  1. /*! echo.js v1.7.0 | (c) 2015 @toddmotto | https://github.com/toddmotto/echo */
  2. (function (root, factory) {
  3. if (typeof define === 'function' && define.amd) {
  4. define(function() {
  5. return factory(root);
  6. });
  7. } else if (typeof exports === 'object') {
  8. module.exports = factory;
  9. } else {
  10. root.echo = factory(root);
  11. }
  12. })(this, function (root) {
  13.  
  14. 'use strict';
  15.  
  16. var echo = {};
  17.  
  18. var callback = function () {};
  19.  
  20. var offset, poll, delay, useDebounce, unload,effectClass;
  21. var classList= 'classList' in document.documentElement ?1:0;
  22. var isHidden = function (element) {
  23. return (element.offsetParent === null);
  24. };
  25.  
  26. var inView = function (element, view) {
  27. if (isHidden(element)) {
  28. return false;
  29. }
  30.  
  31. var box = element.getBoundingClientRect();
  32. return (box.right >= view.l && box.bottom >= view.t && box.left <= view.r && box.top <= view.b);
  33. };
  34.  
  35. var debounceOrThrottle = function () {
  36. if(!useDebounce && !!poll) {
  37. return;
  38. }
  39. clearTimeout(poll);
  40. poll = setTimeout(function(){
  41. echo.render();
  42. poll = null;
  43. }, delay);
  44. };
  45.  
  46. echo.init = function (opts) {
  47. opts = opts || {};
  48. var offsetAll = opts.offset || 0;
  49.  
  50. var offsetVertical = opts.offsetVertical || offsetAll;
  51. var offsetHorizontal = opts.offsetHorizontal || offsetAll;
  52. var optionToInt = function (opt, fallback) {
  53. return parseInt(opt || fallback, 10);
  54. };
  55. offset = {
  56. t: optionToInt(opts.offsetTop, offsetVertical),
  57. b: optionToInt(opts.offsetBottom, offsetVertical),
  58. l: optionToInt(opts.offsetLeft, offsetHorizontal),
  59. r: optionToInt(opts.offsetRight, offsetHorizontal)
  60. };
  61. delay = optionToInt(opts.throttle, 80);
  62. useDebounce = opts.debounce !== false;
  63. effectClass=opts.effectClass;
  64. unload = !!opts.unload;
  65. callback = opts.callback || callback;
  66. echo.render();
  67. if (document.addEventListener) {
  68. root.addEventListener('scroll', debounceOrThrottle, false);
  69. root.addEventListener('load', debounceOrThrottle, false);
  70. } else {
  71. root.attachEvent('onscroll', debounceOrThrottle);
  72. root.attachEvent('onload', debounceOrThrottle);
  73. }
  74. };
  75.  
  76. echo.render = function () {
  77. var nodes = document.querySelectorAll('img[data-echo], [data-echo-background]');
  78. var length = nodes.length;
  79. var src, elem;
  80. var view = {
  81. l: 0 - offset.l,
  82. t: 0 - offset.t,
  83. b: (root.innerHeight || document.documentElement.clientHeight) + offset.b,
  84. r: (root.innerWidth || document.documentElement.clientWidth) + offset.r
  85. };
  86. for (var i = 0; i < length; i++) {
  87. elem = nodes[i];
  88. if (inView(elem, view)) {
  89.  
  90. if (unload) {
  91. elem.setAttribute('data-echo-placeholder', elem.src);
  92. }
  93.  
  94. if (elem.getAttribute('data-echo-background') !== null) {
  95. elem.style.backgroundImage = "url(" + elem.getAttribute('data-echo-background') + ")";
  96.  
  97. }
  98. else {
  99. elem.src = elem.getAttribute('data-echo');
  100.  
  101. }
  102.  
  103. if (!unload) {
  104. if(effectClass){
  105. if (classList){
  106. elem.classList.add(effectClass);
  107. }else{
  108. elem.className += " " + effectClass;
  109. }
  110. }
  111. elem.removeAttribute('data-echo');
  112. elem.removeAttribute('data-echo-background');
  113. }
  114.  
  115. callback(elem, 'load');
  116. }
  117. else if (unload && !!(src = elem.getAttribute('data-echo-placeholder'))) {
  118.  
  119. if (elem.getAttribute('data-echo-background') !== null) {
  120. elem.style.backgroundImage = "url(" + src + ")";
  121. }
  122. else {
  123. elem.src = src;
  124. }
  125.  
  126. elem.removeAttribute('data-echo-placeholder');
  127. callback(elem, 'unload');
  128. }
  129. }
  130. if (!length) {
  131. echo.detach();
  132. }
  133. };
  134.  
  135. echo.detach = function () {
  136. if (document.removeEventListener) {
  137. root.removeEventListener('scroll', debounceOrThrottle);
  138. } else {
  139. root.detachEvent('onscroll', debounceOrThrottle);
  140. }
  141. clearTimeout(poll);
  142. };
  143.  
  144. return echo;
  145.  
  146. });

使用方法

  1. <img src="img/blank.gif" alt="Photo" data-echo="img/photo.jpg">
  2.  
  3. <script src="../echo.js"></script>
  4. <script>
  5. echo.init({
  6. offset: 100,
  7. throttle: 250,
  8. unload: false,
  9. callback: function (element, op) {
  10. console.log(element, 'has been', op + 'ed')
  11. }
  12. });

domready(fn)

  1. function Domready(readyFn) {
  2. if (document.addEventListener) {
  3. document.addEventListener("DOMContentLoaded", function() {
  4. readyFn && readyFn()
  5. }, false)
  6. } else {
  7. var bReady = false;
  8. document.attachEvent("onreadystatechange", function() {
  9. if (bReady) {
  10. return
  11. }
  12. if (document.readyState == "complete" || document.readyState == "interactive") {
  13. bReady = true;
  14. readyFn && readyFn()
  15. }
  16. });
  17. setTimeout(checkDoScroll, 1)
  18. }
  19. function checkDoScroll() {
  20. try {
  21. document.documentElement.doScroll("left");
  22. if (bReady) {
  23. return
  24. }
  25. bReady = true;
  26. readyFn && readyFn()
  27. } catch (e) {
  28. setTimeout(checkDoScroll, 1)
  29. }
  30. }
  31. };

为元素添加on方法

  1. Element.prototype.on = Element.prototype.addEventListener;

为元素添加trigger方法

  1. HTMLElement.prototype.trigger = function (type, data) {
  2. var event = document.createEvent('HTMLEvents');
  3. event.initEvent(type, true, true);
  4. event.data = data || {};
  5. event.eventName = type;
  6. event.target = this;
  7. this.dispatchEvent(event);
  8. return this;
  9. };

  

获取文档完整的高度

  1. //获取文档完整的高度
  2. var getScrollHeight=function () {
  3. return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
  4. }

 

获取当前可是范围的高度

  1. //获取当前可是范围的高度
  2. var getClientHeight=function () {
  3. var clientHeight = 0;
  4. if (document.body.clientHeight && document.documentElement.clientHeight) {
  5. clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
  6. }
  7. else {
  8. clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
  9. }
  10. return clientHeight;
  11. }

  

 。。。。剩下的慢慢添加...

http://www.cnblogs.com/surfaces/

原生js实现 常见的jquery的功能的更多相关文章

  1. 利用原生JS实现类似浏览器查找高亮功能(转载)

    利用原生JS实现类似浏览器查找高亮功能 在完成 Navify 时,增加一个类似浏览器ctrl+f查找并该高亮的功能,在此进行一点总结: 需求 在.content中有许多.box,需要在.box中找出搜 ...

  2. 原生js使用forEach()与jquery使用each遍历数组,return false 的区别

    原生js使用forEach()与jquery使用each()遍历数组,return false 的区别: 1.使用each()遍历数组a,如下: var a=[20,21,22,23,24]; $.e ...

  3. 原生JS研究:学习jquery源码,收集整理常用JS函数

    原生JS研究:学习jquery源码,收集整理常用JS函数: 1. JS获取原生class(getElementsByClass) 转自:http://blog.csdn.net/kongjiea/ar ...

  4. jquery与原生JS实现增加、减小字号功能

    预览效果: 实现代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  5. AJAX初识(原生JS版AJAX和Jquery版AJAX)

    一.什么是JSON 1.介绍 JSON独立于语言,是一种与语言无关的数据格式. JSON指的是JavaScript对象表示法(JavaScript Object Notation) JSON是轻量级的 ...

  6. 原生JS的使用,包括jquery和原生JS获取节点、jquery和原生JS修改属性的比较

    一.前言 相比于JS这条直达终点.满是荆棘的小路,jquery无疑是康庄大道了,足够的简洁.易用给了它辉煌的地位.然而,毕竟是绕着道的插件,当小路走着走着变成大路的时候,曾经的大路也就失去了他自身的优 ...

  7. 原生js拖拽、jQuery拖拽、vue自定义指令拖拽

    原生js拖拽: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  8. 原生js实现ajax与jquery的ajax库,及json

    这是一篇笔记博客, Ajax: 和服务器进行数据交换(异步) 用js实现复杂的原理:用于发送请求的对象在不同的浏览器中是不同的 同源策略:ajax发送请求的url地址与服务器地址必须是同一域名,协议, ...

  9. 【JavaScript框架封装】使用原生js封装的类似于JQuery的框架及核心源码分享(多文件版本)

    这个版本的JQuery是对上一个版本的JQuery,使用了require.js进行了二次封装,基本上把前面的每一个框架封装成为一个单独的模块,最终的目录结构如下: 由于代码量和目录比较多,这个封装好的 ...

随机推荐

  1. sql server实现主从复制

    测试环境 :主机: 数据库sql server08 r2  系统windows server 2008 r2  IP192.168.1.202 丛机:数据库sql server12  系统window ...

  2. php获胜的算法的概率,它可用于刮,大转盘等彩票的算法

    php获胜的算法的概率,它可用于刮,大转盘等彩票的算法. easy,代码里有具体凝视说明.一看就懂 <?php /* * 经典的概率算法, * $proArr是一个预先设置的数组. * 假设数组 ...

  3. JavaScript类数组对象参考

    JavaScript和DOM中有很多类数组对象,它们有以下特点 1.有length属性 2.可以使用[]通过下标访问 3.部分类数组对象使用[]访问成员时不只可以使用下标,还可以使用id或name 4 ...

  4. 为VS2013添加SQLCE的支持

    解决 下载SQL Server Compact Toolbox by ErikEJ并安装 打开VS2013,新建一工程,在“视图>其它窗口>SQL Server Compact Toolb ...

  5. 第五章_JSTL

    5.1.下载JSTL http://jstl.java.net 5.2.JSTL类库 类别 下属功能 URI 前缀 Core 变量支持 http://java.sun.com/jsp/jstl/cor ...

  6. OpenCV Haar AdaBoost源代码改进(比EMCV快6倍)

    这几天研究了OpenCV源代码 Haar AdaBoost算法,作了一下改进 1.去掉了全部动态分配内存的操作.对嵌入式系统有一定的速度提升 2.凝视覆盖了大量关键代码 3.降低了代码一半的体积,而且 ...

  7. android 编译调用C代码

    博客地址:www.zalezone.cn 前言 需求来源 这几天帮别人做一个简单的androidclient,也没什么功能,主要就是调用C代码来对手机的Wifi网络进行设置.于是也就引出了技术难点所在 ...

  8. 解决 - java.lang.OutOfMemoryError: unable to create new native thread

    工作中碰到过这个问题好几次了,觉得有必要总结一下,所以有了这篇文章,这篇文章分为三个部分:认识问题.分析问题.解决问题. 一.认识问题: 首先我们通过下面这个 测试程序 来认识这个问题: 运行的环境  ...

  9. simple factory, factory method, abstract factory

    simple factory good:1 devide implementation and initialization2 use config file can make system more ...

  10. Sql Server远程查询db 表中的数据,以本地

    step 1: sp_configure 'show advanced options', 1; RECONFIGURE; sp_configure 'Ad Hoc Distributed Queri ...