主頁 > 企業開發 > 原生 JavaScript 代替 jQuery【轉】

原生 JavaScript 代替 jQuery【轉】

2020-10-13 13:21:20 企業開發

用原生JavaScript代替jQuery

前端發展很快,現代瀏覽器原生 API 已經足夠好用,我們并不需要為了操作 DOM、Event 等再學習一下 jQuery 的 API,同時由于 React、Angular、Vue 等框架的流行,直接操作 DOM 不再是好的模式,jQuery 使用場景大大減少,本專案總結了大部分 jQuery API 替代的方法,暫時只支持 IE10 以上瀏覽器,

目錄
  • 用原生JavaScript代替jQuery
    • Query Selector
    • CSS & Style
    • DOM Manipulation
    • Ajax
    • Events
    • Utilities
    • Promises
    • Animation
    • Alternatives
    • Browser Support
  • License

Query Selector

常用的 class、id、屬性 選擇器都可以使用 document.querySelectordocument.querySelectorAll 替代,區別是

  • document.querySelector 回傳第一個匹配的 Element
  • document.querySelectorAll 回傳所有匹配的 Element 組成的 NodeList,它可以通過 [].slice.call() 把它轉成 Array
  • 如果匹配不到任何 Element,jQuery 回傳空陣列 [],但 document.querySelector 回傳 null,注意空指標例外,當找不到時,也可以使用 || 設定默認的值,如 document.querySelectorAll(selector) || []

注意:document.querySelectordocument.querySelectorAll 性能很,如果想提高性能,盡量使用 document.getElementByIddocument.getElementsByClassNamedocument.getElementsByTagName

  • 1.0 選擇器查詢

    // jQuery
    $('selector');
    
    // Native
    document.querySelectorAll('selector');
    
  • 1.1 class 查詢

    // jQuery
    $('.class');
    
    // Native
    document.querySelectorAll('.class');
    
    // or
    document.getElementsByClassName('class');
    
  • 1.2 id 查詢

    // jQuery
    $('#id');
    
    // Native
    document.querySelector('#id');
    
    // or
    document.getElementById('id');
    
  • 1.3 屬性查詢

    // jQuery
    $('a[target=_blank]');
    
    // Native
    document.querySelectorAll('a[target=_blank]');
    
  • 1.4 后代查詢

    // jQuery
    $el.find('li');
    
    // Native
    el.querySelectorAll('li');
    
  • 1.5 兄弟及上下元素

    • 兄弟元素

      // jQuery
      $el.siblings();
      
      // Native - latest, Edge13+
      [...el.parentNode.children].filter((child) =>
        child !== el
      );
      // Native (alternative) - latest, Edge13+
      Array.from(el.parentNode.children).filter((child) =>
        child !== el
      );
      // Native - IE10+
      Array.prototype.filter.call(el.parentNode.children, (child) =>
        child !== el
      );
      
    • 上一個元素

      // jQuery
      $el.prev();
      
      // Native
      el.previousElementSibling;
      
      
    • 下一個元素

      // next
      $el.next();
      
      // Native
      el.nextElementSibling;
      
  • 1.6 Closest

    Closest 獲得匹配選擇器的第一個祖先元素,從當前元素開始沿 DOM 樹向上,

    // jQuery
    $el.closest(queryString);
    
    // Native - Only latest, NO IE
    el.closest(selector);
    
    // Native - IE10+
    function closest(el, selector) {
      const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
    
      while (el) {
        if (matchesSelector.call(el, selector)) {
          return el;
        } else {
          el = el.parentElement;
        }
      }
      return null;
    }
    
  • 1.7 Parents Until

    獲取當前每一個匹配元素集的祖先,不包括匹配元素的本身,

    // jQuery
    $el.parentsUntil(selector, filter);
    
    // Native
    function parentsUntil(el, selector, filter) {
      const result = [];
      const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
    
      // match start from parent
      el = el.parentElement;
      while (el && !matchesSelector.call(el, selector)) {
        if (!filter) {
          result.push(el);
        } else {
          if (matchesSelector.call(el, filter)) {
            result.push(el);
          }
        }
        el = el.parentElement;
      }
      return result;
    }
    
  • 1.8 Form

    • Input/Textarea

      // jQuery
      $('#my-input').val();
      
      // Native
      document.querySelector('#my-input').value;
      
    • 獲取 e.currentTarget 在 .radio 中的陣列索引

      // jQuery
      $('.radio').index(e.currentTarget);
      
      // Native
      Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
      
  • 1.9 Iframe Contents

    jQuery 物件的 iframe contents() 回傳的是 iframe 內的 document

    • Iframe contents

      // jQuery
      $iframe.contents();
      
      // Native
      iframe.contentDocument;
      
    • Iframe Query

      // jQuery
      $iframe.contents().find('.css');
      
      // Native
      iframe.contentDocument.querySelectorAll('.css');
      
  • 1.10 獲取 body

    // jQuery
    $('body');
    
    // Native
    document.body;
    
  • 1.11 獲取或設定屬性

    • 獲取屬性

      // jQuery
      $el.attr('foo');
      
      // Native
      el.getAttribute('foo');
      
    • 設定屬性

      // jQuery, note that this works in memory without change the DOM
      $el.attr('foo', 'bar');
      
      // Native
      el.setAttribute('foo', 'bar');
      
    • 獲取 data- 屬性

      // jQuery
      $el.data('foo');
      
      // Native (use `getAttribute`)
      el.getAttribute('data-foo');
      
      // Native (use `dataset` if only need to support IE 11+)
      el.dataset['foo'];
      

CSS & Style

  • 2.1 CSS

    • Get style

      // jQuery
      $el.css("color");
      
      // Native
      // 注意:此處為了解決當 style 值為 auto 時,回傳 auto 的問題
      const win = el.ownerDocument.defaultView;
      
      // null 的意思是不回傳偽類元素
      win.getComputedStyle(el, null).color;
      
    • Set style

      // jQuery
      $el.css({ color: "#ff0011" });
      
      // Native
      el.style.color = '#ff0011';
      
    • Get/Set Styles

      注意,如果想一次設定多個 style,可以參考 oui-dom-utils 中 setStyles 方法

    • Add class

      // jQuery
      $el.addClass(className);
      
      // Native
      el.classList.add(className);
      
    • Remove class

      // jQuery
      $el.removeClass(className);
      
      // Native
      el.classList.remove(className);
      
    • has class

      // jQuery
      $el.hasClass(className);
      
      // Native
      el.classList.contains(className);
      
    • Toggle class

      // jQuery
      $el.toggleClass(className);
      
      // Native
      el.classList.toggle(className);
      
  • 2.2 Width & Height

    Width 與 Height 獲取方法相同,下面以 Height 為例:

    • Window height

      // window height
      $(window).height();
      
      // 含 scrollbar
      window.document.documentElement.clientHeight;
      
      // 不含 scrollbar,與 jQuery 行為一致
      window.innerHeight;
      
    • Document height

      // jQuery
      $(document).height();
      
      // Native
      const body = document.body;
      const html = document.documentElement;
      const height = Math.max(
        body.offsetHeight,
        body.scrollHeight,
        html.clientHeight,
        html.offsetHeight,
        html.scrollHeight
      );
      
    • Element height

      // jQuery
      $el.height();
      
      // Native
      function getHeight(el) {
        const styles = this.getComputedStyle(el);
        const height = el.offsetHeight;
        const borderTopWidth = parseFloat(styles.borderTopWidth);
        const borderBottomWidth = parseFloat(styles.borderBottomWidth);
        const paddingTop = parseFloat(styles.paddingTop);
        const paddingBottom = parseFloat(styles.paddingBottom);
        return height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;
      }
      
      // 精確到整數(border-box 時為 height - border 值,content-box 時為 height + padding 值)
      el.clientHeight;
      
      // 精確到小數(border-box 時為 height 值,content-box 時為 height + padding + border 值)
      el.getBoundingClientRect().height;
      
  • 2.3 Position & Offset

    • Position

      獲得匹配元素相對父元素的偏移

      // jQuery
      $el.position();
      
      // Native
      { left: el.offsetLeft, top: el.offsetTop }
      
    • Offset

      獲得匹配元素相對檔案的偏移

      // jQuery
      $el.offset();
      
      // Native
      function getOffset (el) {
        const box = el.getBoundingClientRect();
      
        return {
          top: box.top + window.pageYOffset - document.documentElement.clientTop,
          left: box.left + window.pageXOffset - document.documentElement.clientLeft
        }
      }
      
  • 2.4 Scroll Top

    獲取元素滾動條垂直位置,

    // jQuery
    $(window).scrollTop();
    
    // Native
    (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    

DOM Manipulation

  • 3.1 Remove

    從 DOM 中移除元素,

    // jQuery
    $el.remove();
    
    // Native
    el.parentNode.removeChild(el);
    
    // Native - Only latest, NO IE
    el.remove();
    
  • 3.2 Text

    • Get text

      回傳指定元素及其后代的文本內容,

      // jQuery
      $el.text();
      
      // Native
      el.textContent;
      
    • Set text

      設定元素的文本內容,

      // jQuery
      $el.text(string);
      
      // Native
      el.textContent = string;
      
  • 3.3 HTML

    • Get HTML

      // jQuery
      $el.html();
      
      // Native
      el.innerHTML;
      
    • Set HTML

      // jQuery
      $el.html(htmlString);
      
      // Native
      el.innerHTML = htmlString;
      
  • 3.4 Append

    Append 插入到子節點的末尾

    // jQuery
    $el.append("<div id='container'>hello</div>");
    
    // Native (HTML string)
    el.insertAdjacentHTML('beforeend', '<div id="container">Hello World</div>');
    
    // Native (Element)
    el.appendChild(newEl);
    
  • 3.5 Prepend

    // jQuery
    $el.prepend("<div id='container'>hello</div>");
    
    // Native (HTML string)
    el.insertAdjacentHTML('afterbegin', '<div id="container">Hello World</div>');
    
    // Native (Element)
    el.insertBefore(newEl, el.firstChild);
    
  • 3.6 insertBefore

    在選中元素前插入新節點

    // jQuery
    $newEl.insertBefore(queryString);
    
    // Native (HTML string)
    el.insertAdjacentHTML('beforebegin ', '<div id="container">Hello World</div>');
    
    // Native (Element)
    const el = document.querySelector(selector);
    if (el.parentNode) {
      el.parentNode.insertBefore(newEl, el);
    }
    
  • 3.7 insertAfter

    在選中元素后插入新節點

    // jQuery
    $newEl.insertAfter(queryString);
    
    // Native (HTML string)
    el.insertAdjacentHTML('afterend', '<div id="container">Hello World</div>');
    
    // Native (Element)
    const el = document.querySelector(selector);
    if (el.parentNode) {
      el.parentNode.insertBefore(newEl, el.nextSibling);
    }
    
  • 3.8 is

    如果匹配給定的選擇器,回傳true

    // jQuery
    $el.is(selector);
    
    // Native
    el.matches(selector);
    
  • 3.9 clone

    深拷貝被選元素,(生成被選元素的副本,包含子節點、文本和屬性,)

    //jQuery
    $el.clone();
    
    //Native
    //深拷貝添加引數'true'
    el.cloneNode();
    
  • 3.10 empty

    移除所有子節點

    //jQuery
    $el.empty();
    
    //Native
    el.innerHTML = '';
    
  • 3.11 wrap

    把每個被選元素放置在指定的HTML結構中,

    //jQuery
    $(".inner").wrap('<div ></div>');
    
    //Native
    Array.prototype.forEach.call(document.querySelector('.inner'), (el) => {
      const wrapper = document.createElement('div');
      wrapper.className = 'wrapper';
      el.parentNode.insertBefore(wrapper, el);
      el.parentNode.removeChild(el);
      wrapper.appendChild(el);
    });
    
  • 3.12 unwrap

    移除被選元素的父元素的DOM結構

    // jQuery
    $('.inner').unwrap();
    
    // Native
    Array.prototype.forEach.call(document.querySelectorAll('.inner'), (el) => {
          let elParentNode = el.parentNode
    
          if(elParentNode !== document.body) {
              elParentNode.parentNode.insertBefore(el, elParentNode)
              elParentNode.parentNode.removeChild(elParentNode)
          }
    });
    
  • 3.13 replaceWith

    用指定的元素替換被選的元素

    //jQuery
    $('.inner').replaceWith('<div ></div>');
    
    //Native
    Array.prototype.forEach.call(document.querySelectorAll('.inner'),(el) => {
      const outer = document.createElement("div");
      outer.className = "outer";
      el.parentNode.insertBefore(outer, el);
      el.parentNode.removeChild(el);
    });
    
  • 3.14 simple parse

    決議 HTML/SVG/XML 字串

    // jQuery
    $(`<ol>
      <li>a</li>
      <li>b</li>
    </ol>
    <ol>
      <li>c</li>
      <li>d</li>
    </ol>`);
    
    // Native
    range = document.createRange();
    parse = range.createContextualFragment.bind(range);
    
    parse(`<ol>
      <li>a</li>
      <li>b</li>
    </ol>
    <ol>
      <li>c</li>
      <li>d</li>
    </ol>`);
    

Ajax

Fetch API 是用于替換 XMLHttpRequest 處理 ajax 的新標準,Chrome 和 Firefox 均支持,舊瀏覽器可以使用 polyfills 提供支持,

IE9+ 請使用 github/fetch,IE8+ 請使用 fetch-ie8,JSONP 請使用 fetch-jsonp,

  • 4.1 從服務器讀取資料并替換匹配元素的內容,

    // jQuery
    $(selector).load(url, completeCallback)
    
    // Native
    fetch(url).then(data =https://www.cnblogs.com/KillBugMe/p/> data.text()).then(data => {
      document.querySelector(selector).innerHTML = data
    }).then(completeCallback)
    

Events

完整地替代命名空間和事件代理,鏈接到 https://github.com/oneuijs/oui-dom-events

  • 5.0 Document ready by DOMContentLoaded

    // jQuery
    $(document).ready(eventHandler);
    
    // Native
    // 檢測 DOMContentLoaded 是否已完成
    if (document.readyState !== 'loading') {
      eventHandler();
    } else {
      document.addEventListener('DOMContentLoaded', eventHandler);
    }
    
  • 5.1 使用 on 系結事件

    // jQuery
    $el.on(eventName, eventHandler);
    
    // Native
    el.addEventListener(eventName, eventHandler);
    
  • 5.2 使用 off 解綁事件

    // jQuery
    $el.off(eventName, eventHandler);
    
    // Native
    el.removeEventListener(eventName, eventHandler);
    
  • 5.3 Trigger

    // jQuery
    $(el).trigger('custom-event', {key1: 'data'});
    
    // Native
    if (window.CustomEvent) {
      const event = new CustomEvent('custom-event', {detail: {key1: 'data'}});
    } else {
      const event = document.createEvent('CustomEvent');
      event.initCustomEvent('custom-event', true, true, {key1: 'data'});
    }
    
    el.dispatchEvent(event);
    

Utilities

大部分實用工具都能在 native API 中找到. 其他高級功能可以選用專注于該領域的穩定性和性能都更好的庫來代替,推薦 lodash,

  • 6.1 基本工具

    • isArray

    檢測引數是不是陣列,

    // jQuery
    $.isArray(range);
    
    // Native
    Array.isArray(range);
    
    • isWindow

    檢測引數是不是 window,

    // jQuery
    $.isWindow(obj);
    
    // Native
    function isWindow(obj) {
      return obj !== null && obj !== undefined && obj === obj.window;
    }
    
    • inArray

    在陣列中搜索指定值并回傳索引 (找不到則回傳 -1),

    // jQuery
    $.inArray(item, array);
    
    // Native
    array.indexOf(item) > -1;
    
    // ES6-way
    array.includes(item);
    
    • isNumeric

    檢測傳入的引數是不是數字,
    Use typeof to decide the type or the type example for better accuracy.

    // jQuery
    $.isNumeric(item);
    
    // Native
    function isNumeric(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    
    • isFunction

    檢測傳入的引數是不是 JavaScript 函式物件,

    // jQuery
    $.isFunction(item);
    
    // Native
    function isFunction(item) {
      if (typeof item === 'function') {
        return true;
      }
      var type = Object.prototype.toString(item);
      return type === '[object Function]' || type === '[object GeneratorFunction]';
    }
    
    • isEmptyObject

    檢測物件是否為空 (包括不可列舉屬性).

    // jQuery
    $.isEmptyObject(obj);
    
    // Native
    function isEmptyObject(obj) {
      return Object.keys(obj).length === 0;
    }
    
    • isPlainObject

    檢測是不是扁平物件 (使用 “{}” 或 “new Object” 創建).

    // jQuery
    $.isPlainObject(obj);
    
    // Native
    function isPlainObject(obj) {
      if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) {
        return false;
      }
    
      if (obj.constructor &&
          !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) {
        return false;
      }
    
      return true;
    }
    
    • extend

    合并多個物件的內容到第一個物件,
    object.assign 是 ES6 API,也可以使用 polyfill,

    // jQuery
    $.extend({}, defaultOpts, opts);
    
    // Native
    Object.assign({}, defaultOpts, opts);
    
    • trim

    移除字串頭尾空白,

    // jQuery
    $.trim(string);
    
    // Native
    string.trim();
    
    • map

    將陣列或物件轉化為包含新內容的陣列,

    // jQuery
    $.map(array, (value, index) => {
    });
    
    // Native
    array.map((value, index) => {
    });
    
    • each

    輪詢函式,可用于平滑的輪詢物件和陣列,

    // jQuery
    $.each(array, (index, value) => {
    });
    
    // Native
    array.forEach((value, index) => {
    });
    
    • grep

    找到陣列中符合過濾函式的元素,

    // jQuery
    $.grep(array, (value, index) => {
    });
    
    // Native
    array.filter((value, index) => {
    });
    
    • type

    檢測物件的 JavaScript [Class] 內部型別,

    // jQuery
    $.type(obj);
    
    // Native
    function type(item) {
      const reTypeOf = /(?:^\[object\s(.*?)\]$)/;
      return Object.prototype.toString.call(item)
        .replace(reTypeOf, '$1')
        .toLowerCase();
    }
    
    • merge

    合并第二個陣列內容到第一個陣列,

    // jQuery
    $.merge(array1, array2);
    
    // Native
    // 使用 concat,不能去除重復值
    function merge(...args) {
      return [].concat(...args)
    }
    
    // ES6,同樣不能去除重復值
    array1 = [...array1, ...array2]
    
    // 使用 Set,可以去除重復值
    function merge(...args) {
      return Array.from(new Set([].concat(...args)))
    }
    
    • now

    回傳當前時間的數字呈現,

    // jQuery
    $.now();
    
    // Native
    Date.now();
    
    • proxy

    傳入函式并回傳一個新函式,該函式系結指定背景關系,

    // jQuery
    $.proxy(fn, context);
    
    // Native
    fn.bind(context);
    
    • makeArray

    類陣列物件轉化為真正的 JavaScript 陣列,

    // jQuery
    $.makeArray(arrayLike);
    
    // Native
    Array.prototype.slice.call(arrayLike);
    
    // ES6-way
    Array.from(arrayLike);
    
  • 6.2 包含

    檢測 DOM 元素是不是其他 DOM 元素的后代.

    // jQuery
    $.contains(el, child);
    
    // Native
    el !== child && el.contains(child);
    
  • 6.3 Globaleval

    全域執行 JavaScript 代碼,

    // jQuery
    $.globaleval(code);
    
    // Native
    function Globaleval(code) {
      const script = document.createElement('script');
      script.text = code;
    
      document.head.appendChild(script).parentNode.removeChild(script);
    }
    
    // Use eval, but context of eval is current, context of $.Globaleval is global.
    eval(code);
    
  • 6.4 決議

    • parseHTML

    決議字串為 DOM 節點陣列.

    // jQuery
    $.parseHTML(htmlString);
    
    // Native
    function parseHTML(string) {
      const context = document.implementation.createHTMLDocument();
    
      // Set the base href for the created document so any parsed elements with URLs
      // are based on the document's URL
      const base = context.createElement('base');
      base.href = https://www.cnblogs.com/KillBugMe/p/document.location.href;
      context.head.appendChild(base);
    
      context.body.innerHTML = string;
      return context.body.children;
    }
    
    • parseJSON

    傳入格式正確的 JSON 字串并回傳 JavaScript 值.

    // jQuery
    $.parseJSON(str);
    
    // Native
    JSON.parse(str);
    

Promises

Promise 代表異步操作的最終結果,jQuery 用它自己的方式處理 promises,原生 JavaScript 遵循 Promises/A+ 標準實作了最小 API 來處理 promises,

  • 7.1 done, fail, always

    done 會在 promise 解決時呼叫,fail 會在 promise 拒絕時呼叫,always 總會呼叫,

    // jQuery
    $promise.done(doneCallback).fail(failCallback).always(alwaysCallback)
    
    // Native
    promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)
    
  • 7.2 when

    when 用于處理多個 promises,當全部 promises 被解決時回傳,當任一 promise 被拒絕時拒絕,

    // jQuery
    $.when($promise1, $promise2).done((promise1Result, promise2Result) => {
    });
    
    // Native
    Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});
    
  • 7.3 Deferred

    Deferred 是創建 promises 的一種方式,

    // jQuery
    function asyncFunc() {
      const defer = new $.Deferred();
      setTimeout(() => {
        if(true) {
          defer.resolve('some_value_computed_asynchronously');
        } else {
          defer.reject('failed');
        }
      }, 1000);
    
      return defer.promise();
    }
    
    // Native
    function asyncFunc() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (true) {
            resolve('some_value_computed_asynchronously');
          } else {
            reject('failed');
          }
        }, 1000);
      });
    }
    
    // Deferred way
    function defer() {
      const deferred = {};
      const promise = new Promise((resolve, reject) => {
        deferred.resolve = resolve;
        deferred.reject = reject;
      });
    
      deferred.promise = () => {
        return promise;
      };
    
      return deferred;
    }
    
    function asyncFunc() {
      const defer = defer();
      setTimeout(() => {
        if(true) {
          defer.resolve('some_value_computed_asynchronously');
        } else {
          defer.reject('failed');
        }
      }, 1000);
    
      return defer.promise();
    }
    

Animation

  • 8.1 Show & Hide

    // jQuery
    $el.show();
    $el.hide();
    
    // Native
    // 更多 show 方法的細節詳見 https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363
    el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block';
    el.style.display = 'none';
    
  • 8.2 Toggle

    顯示或隱藏元素,

    // jQuery
    $el.toggle();
    
    // Native
    if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') {
      el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block';
    } else {
      el.style.display = 'none';
    }
    
  • 8.3 FadeIn & FadeOut

    // jQuery
    $el.fadeIn(3000);
    $el.fadeOut(3000);
    
    // Native
    el.style.transition = 'opacity 3s';
    // fadeIn
    el.style.opacity = '1';
    // fadeOut
    el.style.opacity = '0';
    
  • 8.4 FadeTo

    調整元素透明度,

    // jQuery
    $el.fadeTo('slow',0.15);
    // Native
    el.style.transition = 'opacity 3s'; // 假設 'slow' 等于 3 秒
    el.style.opacity = '0.15';
    
  • 8.5 FadeToggle

    影片調整透明度用來顯示或隱藏,

    // jQuery
    $el.fadeToggle();
    
    // Native
    el.style.transition = 'opacity 3s';
    const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null);
    if (opacity === '1') {
      el.style.opacity = '0';
    } else {
      el.style.opacity = '1';
    }
    
  • 8.6 SlideUp & SlideDown

    // jQuery
    $el.slideUp();
    $el.slideDown();
    
    // Native
    const originHeight = '100px';
    el.style.transition = 'height 3s';
    // slideUp
    el.style.height = '0px';
    // slideDown
    el.style.height = originHeight;
    
  • 8.7 SlideToggle

    滑動切換顯示或隱藏,

    // jQuery
    $el.slideToggle();
    
    // Native
    const originHeight = '100px';
    el.style.transition = 'height 3s';
    const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null);
    if (parseInt(height, 10) === 0) {
      el.style.height = originHeight;
    }
    else {
     el.style.height = '0px';
    }
    
  • 8.8 Animate

    執行一系列 CSS 屬性影片,

    // jQuery
    $el.animate({ params }, speed);
    
    // Native
    el.style.transition = 'all ' + speed;
    Object.keys(params).forEach((key) =>
      el.style[key] = params[key];
    )
    

Alternatives

  • 你可能不需要 jQuery (You Might Not Need jQuery) - 如何使用原生 JavaScript 實作通用事件,元素,ajax 等用法,
  • npm-dom 以及 webmodules - 在 NPM 上提供獨立 DOM 模塊的組織

Browser Support

Chrome Firefox IE Opera Safari
Latest ? Latest ? 10+ ? Latest ? 6.1+ ?

License

MIT

原文鏈接:https://github.com/nefe/You-Dont-Need-jQuery

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/170826.html

標籤:JavaScript

上一篇:Javascript模塊化開發3——Grunt之預處理

下一篇:JavaScript 之 物件屬性的特性 和defineProperty方法

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用Django Rest framework搭建Blog

    在前面的Blog例子中我們使用的是GraphQL, 雖然GraphQL的使用處于上升趨勢,但是Rest API還是使用的更廣泛一些. 所以還是決定回到傳統的rest api framework上來, Django rest framework的官網上給了一個很好用的QuickStart, 我參考Qu ......

    uj5u.com 2023-04-20 08:17:54 more
  • 記錄-new Date() 我忍你很久了!

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 大家平時在開發的時候有沒被new Date()折磨過?就是它的諸多怪異的設定讓你每每用的時候,都可能不小心踩坑。造成程式意外出錯,卻一下子找不到問題出處,那叫一個煩透了…… 下面,我就列舉它的“四宗罪”及應用思考 可惡的四宗罪 1. Sa ......

    uj5u.com 2023-04-20 08:17:47 more
  • 使用Vue.js實作文字跑馬燈效果

    實作文字跑馬燈效果,首先用到 substring()截取 和 setInterval計時器 clearInterval()清除計時器 效果如下: 實作代碼如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ......

    uj5u.com 2023-04-20 08:12:31 more
  • JavaScript 運算子

    JavaScript 運算子/運算子 在 JavaScript 中,有一些運算子可以使代碼更簡潔、易讀和高效。以下是一些常見的運算子: 1、可選鏈運算子(optional chaining operator) ?.是可選鏈運算子(optional chaining operator)。?. 可選鏈操 ......

    uj5u.com 2023-04-20 08:02:25 more
  • CSS—相對單位rem

    一、概述 rem是一個相對長度單位,它的單位長度取決于根標簽html的字體尺寸。rem即root em的意思,中文翻譯為根em。瀏覽器的文本尺寸一般默認為16px,即默認情況下: 1rem = 16px rem布局原理:根據CSS媒體查詢功能,更改根標簽的字體尺寸,實作rem單位隨螢屏尺寸的變化,如 ......

    uj5u.com 2023-04-20 08:02:21 more
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 08:01:50 more
  • 如何在 vue3 中使用 jsx/tsx?

    我們都知道,通常情況下我們使用 vue 大多都是用的 SFC(Signle File Component)單檔案組件模式,即一個組件就是一個檔案,但其實 Vue 也是支持使用 JSX 來撰寫組件的。這里不討論 SFC 和 JSX 的好壞,這個仁者見仁智者見智。本篇文章旨在帶領大家快速了解和使用 Vu ......

    uj5u.com 2023-04-20 08:01:37 more
  • 【Vue2.x原始碼系列06】計算屬性computed原理

    本章目標:計算屬性是如何實作的?計算屬性快取原理以及洋蔥模型的應用?在初始化Vue實體時,我們會給每個計算屬性都創建一個對應watcher,我們稱之為計算屬性watcher ......

    uj5u.com 2023-04-20 08:01:31 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:01:10 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:00:32 more