资讯专栏INFORMATION COLUMN

原生js替换jQuery各种方法-中文版

lylwyy2016 / 2514人阅读

摘要:本项目总结了大部分替代的方法,暂时只支持以上浏览器。返回指定元素及其后代的文本内容。从服务器读取数据并替换匹配元素的内容。用它自己的方式处理,原生遵循标准实现了最小来处理。当全部被解决时返回,当任一被拒绝时拒绝。是创建的一种方式。

原文https://github.com/nefe/You-D...

You Don"t Need jQuery

前端发展很快,现代浏览器原生 API 已经足够好用。我们并不需要为了操作 DOM、Event 等再学习一下 jQuery 的 API。同时由于 React、Angular、Vue 等框架的流行,直接操作 DOM 不再是好的模式,jQuery 使用场景大大减少。本项目总结了大部分 jQuery API 替代的方法,暂时只支持 IE10 以上浏览器。

目录

Translations

Query Selector

CSS & Style

DOM Manipulation

Ajax

Events

Utilities

Promises

Animation

Alternatives

Browser Support

Translations

한국어

简体中文

Bahasa Melayu

Bahasa Indonesia

Português(PT-BR)

Tiếng Việt Nam

Español

Русский

Кыргызча

Türkçe

Italiano

Français

日本語

Polski

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) || []

</>复制代码

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

1.0 选择器查询

</>复制代码

  1. // jQuery
  2. $("selector");
  3. // Native
  4. document.querySelectorAll("selector");

1.1 class 查询

</>复制代码

  1. // jQuery
  2. $(".class");
  3. // Native
  4. document.querySelectorAll(".class");
  5. // or
  6. document.getElementsByClassName("class");

1.2 id 查询

</>复制代码

  1. // jQuery
  2. $("#id");
  3. // Native
  4. document.querySelector("#id");
  5. // or
  6. document.getElementById("id");

1.3 属性查询

</>复制代码

  1. // jQuery
  2. $("a[target=_blank]");
  3. // Native
  4. document.querySelectorAll("a[target=_blank]");

1.4 后代查询

</>复制代码

  1. // jQuery
  2. $el.find("li");
  3. // Native
  4. el.querySelectorAll("li");

1.5 兄弟及上下元素

兄弟元素

</>复制代码

  1. // jQuery
  2. $el.siblings();
  3. // Native - latest, Edge13+
  4. [...el.parentNode.children].filter((child) =>
  5. child !== el
  6. );
  7. // Native (alternative) - latest, Edge13+
  8. Array.from(el.parentNode.children).filter((child) =>
  9. child !== el
  10. );
  11. // Native - IE10+
  12. Array.prototype.filter.call(el.parentNode.children, (child) =>
  13. child !== el
  14. );

上一个元素

</>复制代码

  1. // jQuery
  2. $el.prev();
  3. // Native
  4. el.previousElementSibling;

下一个元素

</>复制代码

  1. // next
  2. $el.next();
  3. // Native
  4. el.nextElementSibling;

1.6 Closest

Closest 获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。

</>复制代码

  1. // jQuery
  2. $el.closest(queryString);
  3. // Native - Only latest, NO IE
  4. el.closest(selector);
  5. // Native - IE10+
  6. function closest(el, selector) {
  7. const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
  8. while (el) {
  9. if (matchesSelector.call(el, selector)) {
  10. return el;
  11. } else {
  12. el = el.parentElement;
  13. }
  14. }
  15. return null;
  16. }

1.7 Parents Until

获取当前每一个匹配元素集的祖先,不包括匹配元素的本身。

</>复制代码

  1. // jQuery
  2. $el.parentsUntil(selector, filter);
  3. // Native
  4. function parentsUntil(el, selector, filter) {
  5. const result = [];
  6. const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
  7. // match start from parent
  8. el = el.parentElement;
  9. while (el && !matchesSelector.call(el, selector)) {
  10. if (!filter) {
  11. result.push(el);
  12. } else {
  13. if (matchesSelector.call(el, filter)) {
  14. result.push(el);
  15. }
  16. }
  17. el = el.parentElement;
  18. }
  19. return result;
  20. }

1.8 Form

Input/Textarea

</>复制代码

  1. // jQuery
  2. $("#my-input").val();
  3. // Native
  4. document.querySelector("#my-input").value;

获取 e.currentTarget 在 .radio 中的数组索引

</>复制代码

  1. // jQuery
  2. $(".radio").index(e.currentTarget);
  3. // Native
  4. Array.prototype.indexOf.call(document.querySelectorAll(".radio"), e.currentTarget);

1.9 Iframe Contents

jQuery 对象的 iframe contents() 返回的是 iframe 内的 document

Iframe contents

</>复制代码

  1. // jQuery
  2. $iframe.contents();
  3. // Native
  4. iframe.contentDocument;

Iframe Query

</>复制代码

  1. // jQuery
  2. $iframe.contents().find(".css");
  3. // Native
  4. iframe.contentDocument.querySelectorAll(".css");

1.10 获取 body

</>复制代码

  1. // jQuery
  2. $("body");
  3. // Native
  4. document.body;

1.11 获取或设置属性

获取属性

</>复制代码

  1. // jQuery
  2. $el.attr("foo");
  3. // Native
  4. el.getAttribute("foo");

设置属性

</>复制代码

  1. // jQuery, note that this works in memory without change the DOM
  2. $el.attr("foo", "bar");
  3. // Native
  4. el.setAttribute("foo", "bar");

获取 data- 属性

</>复制代码

  1. // jQuery
  2. $el.data("foo");
  3. // Native (use `getAttribute`)
  4. el.getAttribute("data-foo");
  5. // Native (use `dataset` if only need to support IE 11+)
  6. el.dataset["foo"];

⬆ 回到顶部

CSS & Style

2.1 CSS

Get style

</>复制代码

  1. // jQuery
  2. $el.css("color");
  3. // Native
  4. // 注意:此处为了解决当 style 值为 auto 时,返回 auto 的问题
  5. const win = el.ownerDocument.defaultView;
  6. // null 的意思是不返回伪类元素
  7. win.getComputedStyle(el, null).color;

Set style

</>复制代码

  1. // jQuery
  2. $el.css({ color: "#ff0011" });
  3. // Native
  4. el.style.color = "#ff0011";

Get/Set Styles

注意,如果想一次设置多个 style,可以参考 oui-dom-utils 中 setStyles 方法

Add class

</>复制代码

  1. // jQuery
  2. $el.addClass(className);
  3. // Native
  4. el.classList.add(className);

Remove class

</>复制代码

  1. // jQuery
  2. $el.removeClass(className);
  3. // Native
  4. el.classList.remove(className);

has class

</>复制代码

  1. // jQuery
  2. $el.hasClass(className);
  3. // Native
  4. el.classList.contains(className);

Toggle class

</>复制代码

  1. // jQuery
  2. $el.toggleClass(className);
  3. // Native
  4. el.classList.toggle(className);

2.2 Width & Height

Width 与 Height 获取方法相同,下面以 Height 为例:

Window height

</>复制代码

  1. // window height
  2. $(window).height();
  3. // 含 scrollbar
  4. window.document.documentElement.clientHeight;
  5. // 不含 scrollbar,与 jQuery 行为一致
  6. window.innerHeight;

Document height

</>复制代码

  1. // jQuery
  2. $(document).height();
  3. // Native
  4. const body = document.body;
  5. const html = document.documentElement;
  6. const height = Math.max(
  7. body.offsetHeight,
  8. body.scrollHeight,
  9. html.clientHeight,
  10. html.offsetHeight,
  11. html.scrollHeight
  12. );

Element height

</>复制代码

  1. // jQuery
  2. $el.height();
  3. // Native
  4. function getHeight(el) {
  5. const styles = this.getComputedStyle(el);
  6. const height = el.offsetHeight;
  7. const borderTopWidth = parseFloat(styles.borderTopWidth);
  8. const borderBottomWidth = parseFloat(styles.borderBottomWidth);
  9. const paddingTop = parseFloat(styles.paddingTop);
  10. const paddingBottom = parseFloat(styles.paddingBottom);
  11. return height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;
  12. }
  13. // 精确到整数(border-box 时为 height - border 值,content-box 时为 height + padding 值)
  14. el.clientHeight;
  15. // 精确到小数(border-box 时为 height 值,content-box 时为 height + padding + border 值)
  16. el.getBoundingClientRect().height;

2.3 Position & Offset

Position

获得匹配元素相对父元素的偏移

</>复制代码

  1. // jQuery
  2. $el.position();
  3. // Native
  4. { left: el.offsetLeft, top: el.offsetTop }

Offset

获得匹配元素相对文档的偏移

</>复制代码

  1. // jQuery
  2. $el.offset();
  3. // Native
  4. function getOffset (el) {
  5. const box = el.getBoundingClientRect();
  6. return {
  7. top: box.top + window.pageYOffset - document.documentElement.clientTop,
  8. left: box.left + window.pageXOffset - document.documentElement.clientLeft
  9. }
  10. }

2.4 Scroll Top

获取元素滚动条垂直位置。

</>复制代码

  1. // jQuery
  2. $(window).scrollTop();
  3. // Native
  4. (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;

⬆ 回到顶部

DOM Manipulation

3.1 Remove

从 DOM 中移除元素。

</>复制代码

  1. // jQuery
  2. $el.remove();
  3. // Native
  4. el.parentNode.removeChild(el);

3.2 Text

Get text

返回指定元素及其后代的文本内容。

</>复制代码

  1. // jQuery
  2. $el.text();
  3. // Native
  4. el.textContent;

Set text

设置元素的文本内容。

</>复制代码

  1. // jQuery
  2. $el.text(string);
  3. // Native
  4. el.textContent = string;

3.3 HTML

Get HTML

</>复制代码

  1. // jQuery
  2. $el.html();
  3. // Native
  4. el.innerHTML;

Set HTML

</>复制代码

  1. // jQuery
  2. $el.html(htmlString);
  3. // Native
  4. el.innerHTML = htmlString;

3.4 Append

Append 插入到子节点的末尾

</>复制代码

  1. // jQuery
  2. $el.append("
    hello
    ");
  3. // Native (HTML string)
  4. el.insertAdjacentHTML("beforeend", "
    Hello World
    ");
  5. // Native (Element)
  6. el.appendChild(newEl);

3.5 Prepend

</>复制代码

  1. // jQuery
  2. $el.prepend("
    hello
    ");
  3. // Native (HTML string)
  4. el.insertAdjacentHTML("afterbegin", "
    Hello World
    ");
  5. // Native (Element)
  6. el.insertBefore(newEl, el.firstChild);

3.6 insertBefore

在选中元素前插入新节点

</>复制代码

  1. // jQuery
  2. $newEl.insertBefore(queryString);
  3. // Native (HTML string)
  4. el.insertAdjacentHTML("beforebegin ", "
    Hello World
    ");
  5. // Native (Element)
  6. const el = document.querySelector(selector);
  7. if (el.parentNode) {
  8. el.parentNode.insertBefore(newEl, el);
  9. }

3.7 insertAfter

在选中元素后插入新节点

</>复制代码

  1. // jQuery
  2. $newEl.insertAfter(queryString);
  3. // Native (HTML string)
  4. el.insertAdjacentHTML("afterend", "
    Hello World
    ");
  5. // Native (Element)
  6. const el = document.querySelector(selector);
  7. if (el.parentNode) {
  8. el.parentNode.insertBefore(newEl, el.nextSibling);
  9. }

3.8 is

如果匹配给定的选择器,返回true

</>复制代码

  1. // jQuery
  2. $el.is(selector);
  3. // Native
  4. el.matches(selector);

3.9 clone

深拷贝被选元素。(生成被选元素的副本,包含子节点、文本和属性。)

</>复制代码

  1. //jQuery
  2. $el.clone();
  3. //Native
  4. el.cloneNode();
  5. //深拷贝添加参数‘true

3.10 empty

移除所有子节点

</>复制代码

  1. //jQuery
  2. $el.empty();
  3. //Native
  4. el.innerHTML = "";

3.11 wrap

把每个被选元素放置在指定的HTML结构中。

</>复制代码

  1. //jQuery
  2. $(".inner").wrap("
    ");
  3. //Native
  4. Array.prototype.forEach.call(document.querySelector(".inner"), (el) => {
  5. const wrapper = document.createElement("div");
  6. wrapper.className = "wrapper";
  7. el.parentNode.insertBefore(wrapper, el);
  8. el.parentNode.removeChild(el);
  9. wrapper.appendChild(el);
  10. });

3.12 unwrap

移除被选元素的父元素的DOM结构

</>复制代码

  1. // jQuery
  2. $(".inner").unwrap();
  3. // Native
  4. Array.prototype.forEach.call(document.querySelectorAll(".inner"), (el) => {
  5. let elParentNode = el.parentNode
  6. if(elParentNode !== document.body) {
  7. elParentNode.parentNode.insertBefore(el, elParentNode)
  8. elParentNode.parentNode.removeChild(elParentNode)
  9. }
  10. });

3.13 replaceWith

用指定的元素替换被选的元素

</>复制代码

  1. //jQuery
  2. $(".inner").replaceWith("
    ");
  3. //Native
  4. Array.prototype.forEach.call(document.querySelectorAll(".inner"),(el) => {
  5. const outer = document.createElement("div");
  6. outer.className = "outer";
  7. el.parentNode.insertBefore(outer, el);
  8. el.parentNode.removeChild(el);
  9. });

3.14 simple parse

解析 HTML/SVG/XML 字符串

</>复制代码

  1. // jQuery
  2. $(`
    1. a
    2. b
    1. c
    2. d
    `);
  3. // Native
  4. range = document.createRange();
  5. parse = range.createContextualFragment.bind(range);
  6. parse(`
    1. a
    2. b
    1. c
    2. d
    `);

⬆ 回到顶部

Ajax

Fetch API 是用于替换 XMLHttpRequest 处理 ajax 的新标准,Chrome 和 Firefox 均支持,旧浏览器可以使用 polyfills 提供支持。

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

4.1 从服务器读取数据并替换匹配元素的内容。

</>复制代码

  1. // jQuery
  2. $(selector).load(url, completeCallback)
  3. // Native
  4. fetch(url).then(data => data.text()).then(data => {
  5. document.querySelector(selector).innerHTML = data
  6. }).then(completeCallback)

⬆ 回到顶部

Events

完整地替代命名空间和事件代理,链接到 https://github.com/oneuijs/ou...

5.0 Document ready by DOMContentLoaded

</>复制代码

  1. // jQuery
  2. $(document).ready(eventHandler);
  3. // Native
  4. // 检测 DOMContentLoaded 是否已完成
  5. if (document.readyState !== "loading") {
  6. eventHandler();
  7. } else {
  8. document.addEventListener("DOMContentLoaded", eventHandler);
  9. }

5.1 使用 on 绑定事件

</>复制代码

  1. // jQuery
  2. $el.on(eventName, eventHandler);
  3. // Native
  4. el.addEventListener(eventName, eventHandler);

5.2 使用 off 解绑事件

</>复制代码

  1. // jQuery
  2. $el.off(eventName, eventHandler);
  3. // Native
  4. el.removeEventListener(eventName, eventHandler);

5.3 Trigger

</>复制代码

  1. // jQuery
  2. $(el).trigger("custom-event", {key1: "data"});
  3. // Native
  4. if (window.CustomEvent) {
  5. const event = new CustomEvent("custom-event", {detail: {key1: "data"}});
  6. } else {
  7. const event = document.createEvent("CustomEvent");
  8. event.initCustomEvent("custom-event", true, true, {key1: "data"});
  9. }
  10. el.dispatchEvent(event);

⬆ 回到顶部

Utilities

大部分实用工具都能在 native API 中找到. 其他高级功能可以选用专注于该领域的稳定性和性能都更好的库来代替,推荐 lodash。

6.1 基本工具

isArray

检测参数是不是数组。

</>复制代码

  1. // jQuery
  2. $.isArray(range);
  3. // Native
  4. Array.isArray(range);

isWindow

检测参数是不是 window。

</>复制代码

  1. // jQuery
  2. $.isWindow(obj);
  3. // Native
  4. function isWindow(obj) {
  5. return obj !== null && obj !== undefined && obj === obj.window;
  6. }

inArray

在数组中搜索指定值并返回索引 (找不到则返回 -1)。

</>复制代码

  1. // jQuery
  2. $.inArray(item, array);
  3. // Native
  4. array.indexOf(item) > -1;
  5. // ES6-way
  6. array.includes(item);

isNumeric

检测传入的参数是不是数字。
Use typeof to decide the type or the type example for better accuracy.

</>复制代码

  1. // jQuery
  2. $.isNumeric(item);
  3. // Native
  4. function isNumeric(n) {
  5. return !isNaN(parseFloat(n)) && isFinite(n);
  6. }

isFunction

检测传入的参数是不是 JavaScript 函数对象。

</>复制代码

  1. // jQuery
  2. $.isFunction(item);
  3. // Native
  4. function isFunction(item) {
  5. if (typeof item === "function") {
  6. return true;
  7. }
  8. var type = Object.prototype.toString(item);
  9. return type === "[object Function]" || type === "[object GeneratorFunction]";
  10. }

isEmptyObject

检测对象是否为空 (包括不可枚举属性).

</>复制代码

  1. // jQuery
  2. $.isEmptyObject(obj);
  3. // Native
  4. function isEmptyObject(obj) {
  5. return Object.keys(obj).length === 0;
  6. }

isPlainObject

检测是不是扁平对象 (使用 “{}” 或 “new Object” 创建).

</>复制代码

  1. // jQuery
  2. $.isPlainObject(obj);
  3. // Native
  4. function isPlainObject(obj) {
  5. if (typeof (obj) !== "object" || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) {
  6. return false;
  7. }
  8. if (obj.constructor &&
  9. !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) {
  10. return false;
  11. }
  12. return true;
  13. }

extend

合并多个对象的内容到第一个对象。
object.assign 是 ES6 API,也可以使用 polyfill。

</>复制代码

  1. // jQuery
  2. $.extend({}, defaultOpts, opts);
  3. // Native
  4. Object.assign({}, defaultOpts, opts);

trim

移除字符串头尾空白。

</>复制代码

  1. // jQuery
  2. $.trim(string);
  3. // Native
  4. string.trim();

map

将数组或对象转化为包含新内容的数组。

</>复制代码

  1. // jQuery
  2. $.map(array, (value, index) => {
  3. });
  4. // Native
  5. array.map((value, index) => {
  6. });

each

轮询函数,可用于平滑的轮询对象和数组。

</>复制代码

  1. // jQuery
  2. $.each(array, (index, value) => {
  3. });
  4. // Native
  5. array.forEach((value, index) => {
  6. });

grep

找到数组中符合过滤函数的元素。

</>复制代码

  1. // jQuery
  2. $.grep(array, (value, index) => {
  3. });
  4. // Native
  5. array.filter((value, index) => {
  6. });

type

检测对象的 JavaScript [Class] 内部类型。

</>复制代码

  1. // jQuery
  2. $.type(obj);
  3. // Native
  4. function type(item) {
  5. const reTypeOf = /(?:^[objects(.*?)]$)/;
  6. return Object.prototype.toString.call(item)
  7. .replace(reTypeOf, "$1")
  8. .toLowerCase();
  9. }

merge

合并第二个数组内容到第一个数组。

</>复制代码

  1. // jQuery
  2. $.merge(array1, array2);
  3. // Native
  4. // 使用 concat,不能去除重复值
  5. function merge(...args) {
  6. return [].concat(...args)
  7. }
  8. // ES6,同样不能去除重复值
  9. array1 = [...array1, ...array2]
  10. // 使用 Set,可以去除重复值
  11. function merge(...args) {
  12. return Array.from(new Set([].concat(...args)))
  13. }

now

返回当前时间的数字呈现。

</>复制代码

  1. // jQuery
  2. $.now();
  3. // Native
  4. Date.now();

proxy

传入函数并返回一个新函数,该函数绑定指定上下文。

</>复制代码

  1. // jQuery
  2. $.proxy(fn, context);
  3. // Native
  4. fn.bind(context);

makeArray

类数组对象转化为真正的 JavaScript 数组。

</>复制代码

  1. // jQuery
  2. $.makeArray(arrayLike);
  3. // Native
  4. Array.prototype.slice.call(arrayLike);
  5. // ES6-way
  6. Array.from(arrayLike);

6.2 包含

检测 DOM 元素是不是其他 DOM 元素的后代.

</>复制代码

  1. // jQuery
  2. $.contains(el, child);
  3. // Native
  4. el !== child && el.contains(child);

6.3 Globaleval

全局执行 JavaScript 代码。

</>复制代码

  1. // jQuery
  2. $.globaleval(code);
  3. // Native
  4. function Globaleval(code) {
  5. const script = document.createElement("script");
  6. script.text = code;
  7. document.head.appendChild(script).parentNode.removeChild(script);
  8. }
  9. // Use eval, but context of eval is current, context of $.Globaleval is global.
  10. eval(code);

6.4 解析

parseHTML

解析字符串为 DOM 节点数组.

</>复制代码

  1. // jQuery
  2. $.parseHTML(htmlString);
  3. // Native
  4. function parseHTML(string) {
  5. const context = document.implementation.createHTMLDocument();
  6. // Set the base href for the created document so any parsed elements with URLs
  7. // are based on the document"s URL
  8. const base = context.createElement("base");
  9. base.href = document.location.href;
  10. context.head.appendChild(base);
  11. context.body.innerHTML = string;
  12. return context.body.children;
  13. }

parseJSON

传入格式正确的 JSON 字符串并返回 JavaScript 值.

</>复制代码

  1. // jQuery
  2. $.parseJSON(str);
  3. // Native
  4. JSON.parse(str);

⬆ 回到顶部

Promises

Promise 代表异步操作的最终结果。jQuery 用它自己的方式处理 promises,原生 JavaScript 遵循 Promises/A+ 标准实现了最小 API 来处理 promises。

7.1 done, fail, always

done 会在 promise 解决时调用,fail 会在 promise 拒绝时调用,always 总会调用。

</>复制代码

  1. // jQuery
  2. $promise.done(doneCallback).fail(failCallback).always(alwaysCallback)
  3. // Native
  4. promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)

7.2 when

when 用于处理多个 promises。当全部 promises 被解决时返回,当任一 promise 被拒绝时拒绝。

</>复制代码

  1. // jQuery
  2. $.when($promise1, $promise2).done((promise1Result, promise2Result) => {
  3. });
  4. // Native
  5. Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});

7.3 Deferred

Deferred 是创建 promises 的一种方式。

</>复制代码

  1. // jQuery
  2. function asyncFunc() {
  3. const defer = new $.Deferred();
  4. setTimeout(() => {
  5. if(true) {
  6. defer.resolve("some_value_computed_asynchronously");
  7. } else {
  8. defer.reject("failed");
  9. }
  10. }, 1000);
  11. return defer.promise();
  12. }
  13. // Native
  14. function asyncFunc() {
  15. return new Promise((resolve, reject) => {
  16. setTimeout(() => {
  17. if (true) {
  18. resolve("some_value_computed_asynchronously");
  19. } else {
  20. reject("failed");
  21. }
  22. }, 1000);
  23. });
  24. }
  25. // Deferred way
  26. function defer() {
  27. const deferred = {};
  28. const promise = new Promise((resolve, reject) => {
  29. deferred.resolve = resolve;
  30. deferred.reject = reject;
  31. });
  32. deferred.promise = () => {
  33. return promise;
  34. };
  35. return deferred;
  36. }
  37. function asyncFunc() {
  38. const defer = defer();
  39. setTimeout(() => {
  40. if(true) {
  41. defer.resolve("some_value_computed_asynchronously");
  42. } else {
  43. defer.reject("failed");
  44. }
  45. }, 1000);
  46. return defer.promise();
  47. }

⬆ 回到顶部

Animation

8.1 Show & Hide

</>复制代码

  1. // jQuery
  2. $el.show();
  3. $el.hide();
  4. // Native
  5. // 更多 show 方法的细节详见 https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363
  6. el.style.display = ""|"inline"|"inline-block"|"inline-table"|"block";
  7. el.style.display = "none";

8.2 Toggle

显示或隐藏元素。

</>复制代码

  1. // jQuery
  2. $el.toggle();
  3. // Native
  4. if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === "none") {
  5. el.style.display = ""|"inline"|"inline-block"|"inline-table"|"block";
  6. } else {
  7. el.style.display = "none";
  8. }

8.3 FadeIn & FadeOut

</>复制代码

  1. // jQuery
  2. $el.fadeIn(3000);
  3. $el.fadeOut(3000);
  4. // Native
  5. el.style.transition = "opacity 3s";
  6. // fadeIn
  7. el.style.opacity = "1";
  8. // fadeOut
  9. el.style.opacity = "0";

8.4 FadeTo

调整元素透明度。

</>复制代码

  1. // jQuery
  2. $el.fadeTo("slow",0.15);
  3. // Native
  4. el.style.transition = "opacity 3s"; // 假设 "slow" 等于 3
  5. el.style.opacity = "0.15";

8.5 FadeToggle

动画调整透明度用来显示或隐藏。

</>复制代码

  1. // jQuery
  2. $el.fadeToggle();
  3. // Native
  4. el.style.transition = "opacity 3s";
  5. const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null);
  6. if (opacity === "1") {
  7. el.style.opacity = "0";
  8. } else {
  9. el.style.opacity = "1";
  10. }

8.6 SlideUp & SlideDown

</>复制代码

  1. // jQuery
  2. $el.slideUp();
  3. $el.slideDown();
  4. // Native
  5. const originHeight = "100px";
  6. el.style.transition = "height 3s";
  7. // slideUp
  8. el.style.height = "0px";
  9. // slideDown
  10. el.style.height = originHeight;

8.7 SlideToggle

滑动切换显示或隐藏。

</>复制代码

  1. // jQuery
  2. $el.slideToggle();
  3. // Native
  4. const originHeight = "100px";
  5. el.style.transition = "height 3s";
  6. const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null);
  7. if (parseInt(height, 10) === 0) {
  8. el.style.height = originHeight;
  9. }
  10. else {
  11. el.style.height = "0px";
  12. }

8.8 Animate

执行一系列 CSS 属性动画。

</>复制代码

  1. // jQuery
  2. $el.animate({ params }, speed);
  3. // Native
  4. el.style.transition = "all " + speed;
  5. Object.keys(params).forEach((key) =>
  6. el.style[key] = params[key];
  7. )

⬆ 回到顶部

Alternatives

你可能不需要 jQuery (You Might Not Need jQuery) - 如何使用原生 JavaScript 实现通用事件,元素,ajax 等用法。

npm-dom 以及 webmodules - 在 NPM 上提供独立 DOM 模块的组织

Browser Support
Latest ✔ Latest ✔ 10+ ✔ Latest ✔ 6.1+ ✔
License

MIT

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/98151.html

相关文章

  • Velocity.js简明使用教程(文版上)

    摘要:需要使用,本文未使用,所以暂不考虑。然后,只需要在主函数中调用这些函数,主函数包含方法。每个函数使用关键字存储在常量中。下面是有计时器的主函数。在主函数里调用以上函数注意全局变量。简而言之,不要在动态上下文的回调函数中使用箭头函数。 本文翻译自https://www.sitepoint.com/how... 在本文中,我将介绍Velocity.js,这是一个快速,高性能的JavaScr...

    graf 评论0 收藏0
  • 前端文档收集

    摘要:系列种优化页面加载速度的方法随笔分类中个最重要的技术点常用整理网页性能管理详解离线缓存简介系列编写高性能有趣的原生数组函数数据访问性能优化方案实现的大排序算法一怪对象常用方法函数收集数组的操作面向对象和原型继承中关键词的优雅解释浅谈系列 H5系列 10种优化页面加载速度的方法 随笔分类 - HTML5 HTML5中40个最重要的技术点 常用meta整理 网页性能管理详解 HTML5 ...

    jsbintask 评论0 收藏0
  • 前端文档收集

    摘要:系列种优化页面加载速度的方法随笔分类中个最重要的技术点常用整理网页性能管理详解离线缓存简介系列编写高性能有趣的原生数组函数数据访问性能优化方案实现的大排序算法一怪对象常用方法函数收集数组的操作面向对象和原型继承中关键词的优雅解释浅谈系列 H5系列 10种优化页面加载速度的方法 随笔分类 - HTML5 HTML5中40个最重要的技术点 常用meta整理 网页性能管理详解 HTML5 ...

    muddyway 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<