替代jQuery

1. 选取DOM元素
2. DOM操作
3. 事件的监听
4. 事件的触发
5. document.ready
6. attr方法
7. addClass方法
8. CSS
9. 数据储存
10. Ajax
11. 动画
12. 其它库替代方案 

①选取DOM元素

  • querySelectorAll()方法 返回NodeList对象
  • NodeList转数组: myList = Array.prototype.slice.call(myNodeList);

②dom操作

  • 尾部追加DOM:parent.appendChild(child)
  • 头部插入DOM:parent.insertBefore(child, parent.childNodes[0])
  • 删除DOM元素:child.parentNode.removeChild(child)

③事件监听

  1. Element.prototype.on = Element.prototype.addEventListener;
  2. 可在NodeList对象上也部署这个方法:
     NodeList.prototype.on = function (event, fn) {
         []['forEach'].call(this, function (el) {
           el.on(event, fn);
         });
         return this;
     }
    

④事件的触发

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

    NodeList.prototype.trigger = function (event) {
        []['forEach'].call(this, function (el) {
          el['trigger'](event);
        });
        return this;
      };

⑤document.ready

⑥读写元素属性 attr()

    $("#picture").src = "http://url/to/image";
    this.getAttribute('value');      
    this.getAttibute('href');

⑦addClass()

    document.body.className += ' hasJS';

HTML 5还提供一个classList对象,功能更强大(IE 9不支持)

document.body.classList.add('hasJS');
document.body.classList.remove('hasJS');
document.body.classList.toggle('hasJS');
document.body.classList.contains('hasJS');

⑧设置元素样式 css()

    element.style.color = "red";
    element.style.cssText += 'color:red';

⑨数据储存

    HTML 5   dataset对象:
    element.dataset.user = JSON.stringify(user);
    element.dataset.score = score;

⑩Ajax请求

    function request(type, url, opts, callback) {
        var xhr = new XMLHttpRequest();
        if (typeof opts === 'function') {
          callback = opts;
          opts = null;
        }
        xhr.open(type, url);
        var fd = new FormData();
        if (type === 'POST' && opts) {
          for (var key in opts) {
            fd.append(key, JSON.stringify(opts[key]));
          }
        }
        xhr.onload = function () {
          callback(JSON.parse(xhr.response));
        };
        xhr.send(opts ? fd : null);
    }
    模拟jQuery的get和post方法:
    var get = request.bind(this, 'GET');
    var post = request.bind(this, 'POST');

⑪动画

  • CSS 3代替jq动画 foo.classList.add('animate');
  • CSS 3 新增事件 对动画使用回调函数
  • el.addEventListener("webkitTransitionEnd", transitionEnded);
  • el.addEventListener("transitionend", transitionEnded);

⑫替代方案

name 大小 压缩
zepto.js 55KB 10KB
min.js 200字节
dolla 1.7KB
© QIANSR all right reserved,powered by Gitbook该文件修订时间: 2015-11-26 20:49:20