原生js实现 常见的jquery的功能

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

<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.js

/**
 * 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);

  

原生js实现jQuery的offset函数

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

 

利用数组 forEach的实现

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>

jquery的静态方法 $.each

 

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);
//});

 

hover 方法

<!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, ' ');
    }
}

 

 

 

获取jsonp

 

 

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.οnlοad=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, "");  
}    
 

  

 cookie的操作

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的操作

 

/**
 * 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;

});
View Code

使用方法

  <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')
    }
  });

 

domready(fn)

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)
        }
    }
};
View Code

 

为元素添加on方法

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

 

为元素添加trigger方法

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; 
} 

  

 

 

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

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

转载于:https://www.cnblogs.com/surfaces/p/5130973.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值