jQuery与原生JS相互转化

2023-11-13

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

Query Selector

常用的 class、id、属性 选择器都可以使用 document.querySelector 或 document.querySelectorAll 替代。区别是

  • document.querySelector 返回第一个匹配的 Element

  • document.querySelectorAll 返回所有匹配的 Element 组成的 NodeList。它可以通过 [].slice.call() 把它转成 Array

  • 如果匹配不到任何 Element,jQuery 返回空数组 [],但 document.querySelector 返回 null,注意空指针异常。当找不到时,也可以使用 || 设置默认的值,如 document.querySelectorAll(selector) || []

注意:document.querySelector 和 document.querySelectorAll 性能很。如果想提高性能,尽量使用 document.getElementByIddocument.getElementsByClassName 或 document.getElementsByTagName

1.0 选择器查询

1

2

3

4

5

// jQuery

$('selector');

 

// Native

document.querySelectorAll('selector');

1.1 class 查询 

1

2

3

4

5

6

7

8

// jQuery

$('.class');

 

// Native

document.querySelectorAll('.class');

 

// or

document.getElementsByClassName('class');

1.2 id 查询

1

2

3

4

5

6

7

8

// jQuery

$('#id');

 

// Native

document.querySelector('#id');

 

// or

document.getElementById('id');

1.3 属性查询

1

2

3

4

5

// jQuery

$('a[target=_blank]');

 

// Native

document.querySelectorAll('a[target=_blank]');

1.4 后代查询

1

2

3

4

5

// jQuery

$el.find('li');

 

// Native

el.querySelectorAll('li');

1.5 兄弟及上下元素

 ==>兄弟元素

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

);

==>上一个元素

1

2

3

4

5

// jQuery

$el.prev();

 

// Native

el.previousElementSibling;

==>下一个元素

1

2

3

4

5

// next

$el.next();

 

// Native

el.nextElementSibling;

1.6 Closest

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

1

2

3

4

5

// jQuery

$('#my-input').val();

 

// Native

document.querySelector('#my-input').value;

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

1

2

3

4

5

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

1

2

3

4

5

// jQuery

$iframe.contents();

 

// Native

iframe.contentDocument;

==>Iframe Query

1

2

3

4

5

// jQuery

$iframe.contents().find('.css');

 

// Native

iframe.contentDocument.querySelectorAll('.css');

1.10 获取 body

1

2

3

4

5

// jQuery

$('body');

 

// Native

document.body;

1.11 获取或设置属性

==>获取属性

1

2

3

4

5

// jQuery

$el.attr('foo');

 

// Native

el.getAttribute('foo');

==>设置属性

1

2

3

4

5

// jQuery, note that this works in memory without change the DOM

$el.attr('foo''bar');

 

// Native

el.setAttribute('foo''bar');

==>获取 data- 属性

1

2

3

4

5

6

7

8

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

1

2

3

4

5

6

7

8

9

// jQuery

$el.css("color");

 

// Native

// 注意:此处为了解决当 style 值为 auto 时,返回 auto 的问题

const win = el.ownerDocument.defaultView;

 

// null 的意思是不返回伪类元素

win.getComputedStyle(el, null).color;

==>Set style

1

2

3

4

5

// jQuery

$el.css({ color: "#ff0011" });

 

// Native

el.style.color = '#ff0011';

==>Get/Set Styles

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

==>Add class

1

2

3

4

5

// jQuery

$el.addClass(className);

 

// Native

el.classList.add(className);

==>Remove class

1

2

3

4

5

// jQuery

$el.removeClass(className);

 

// Native

el.classList.remove(className);

==>has class

1

2

3

4

5

// jQuery

$el.hasClass(className);

 

// Native

el.classList.contains(className);

==>Toggle class

1

2

3

4

5

// jQuery

$el.toggleClass(className);

 

// Native

el.classList.toggle(className);

2.2 Width & Height

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

==>Window height

1

2

3

4

5

6

7

8

// window height

$(window).height();

 

// 含 scrollbar

window.document.documentElement.clientHeight;

 

// 不含 scrollbar,与 jQuery 行为一致

window.innerHeight;

==>Document height

1

2

3

4

5

6

7

8

9

10

11

12

13

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

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

1

2

3

4

5

// jQuery

$el.position();

 

// Native

{ left: el.offsetLeft, top: el.offsetTop }

==>Offset

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

1

2

3

4

5

6

7

8

9

10

11

12

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

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

1

2

3

4

5

// jQuery

  $(window).scrollTop();

 

  // Native

  (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;

DOM Manipulation

3.1 Remove

从 DOM 中移除元素。

1

2

3

4

5

// jQuery

$el.remove();

 

// Native

el.parentNode.removeChild(el);

3.2 Text

==>Get text

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

1

2

3

4

5

// jQuery

$el.text();

 

// Native

el.textContent;

==>Set text

设置元素的文本内容。

1

2

3

4

5

// jQuery

$el.text(string);

 

// Native

el.textContent = string;

3.3 HTML

==>Get HTML

1

2

3

4

5

// jQuery

$el.html();

 

// Native

el.innerHTML;

==>Set HTML

1

2

3

4

5

// jQuery

$el.html(htmlString);

 

// Native

el.innerHTML = htmlString;

3.4 Append

Append 插入到子节点的末尾

1

2

3

4

5

6

7

8

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

1

2

3

4

5

6

7

8

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

在选中元素前插入新节点

1

2

3

4

5

6

7

8

9

10

11

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

在选中元素后插入新节点

1

2

3

4

5

6

7

8

9

10

11

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

1

2

3

4

5

// jQuery

$el.is(selector);

 

// Native

el.matches(selector);

3.9 clone

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

1

2

3

4

5

//jQuery

$el.clone();

 

//Native

el.cloneNode();

//深拷贝添加参数‘true’

 3.10 empty

 移除所有子节点

1

2

3

4

5

//jQuery

$el.empty();

 

//Native

el.innerHTML = '';

3.11 wrap

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

1

2

3

4

5

6

7

8

9

10

11

//jQuery

$(".inner").wrap('<div class="wrapper"></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结构

1

2

3

4

5

6

7

8

9

10

11

12

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

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

1

2

3

4

5

6

7

8

9

10

//jQuery

$('.inner').replaceWith('<div class="outer"></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 字符串

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// 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 从服务器读取数据并替换匹配元素的内容。

1

2

3

4

5

6

7

// jQuery

$(selector).load(url, completeCallback)

 

// Native

fetch(url).then(data => 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

1

2

3

4

5

6

7

8

9

10

// jQuery

$(document).ready(eventHandler);

 

// Native

// 检测 DOMContentLoaded 是否已完成

if (document.readyState !== 'loading') {

  eventHandler();

else {

  document.addEventListener('DOMContentLoaded', eventHandler);

}

5.1 使用 on 绑定事件

1

2

3

4

5

// jQuery

$el.on(eventName, eventHandler);

 

// Native

el.addEventListener(eventName, eventHandler);

5.2 使用 off 解绑事件

1

2

3

4

5

// jQuery

$el.off(eventName, eventHandler);

 

// Native

el.removeEventListener(eventName, eventHandler);

5.3 Trigger

1

2

3

4

5

6

7

8

9

10

11

12

// 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'truetrue, {key1: 'data'});

}

 

el.dispatchEvent(event);

Utilities

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

6.1 基本工具

==>isArray

检测参数是不是数组。

1

2

3

4

5

// jQuery

$.isArray(range);

 

// Native

Array.isArray(range);

==>isWindow

检测参数是不是 window。

1

2

3

4

5

6

7

// jQuery

$.isWindow(obj);

 

// Native

function isWindow(obj) {

  return obj !== null && obj !== undefined && obj === obj.window;

}

==>inArray

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

1

2

3

4

5

6

7

8

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

1

2

3

4

5

6

7

// jQuery

$.isNumeric(item);

 

// Native

function isNumeric(n) {

  return !isNaN(parseFloat(n)) && isFinite(n);

}

==>isFunction

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

1

2

3

4

5

6

7

8

9

10

11

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

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

1

2

3

4

5

6

7

// jQuery

$.isEmptyObject(obj);

 

// Native

function isEmptyObject(obj) {

  return Object.keys(obj).length === 0;

}

==>isPlainObject

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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

1

2

3

4

5

// jQuery

$.extend({}, defaultOpts, opts);

 

// Native

Object.assign({}, defaultOpts, opts);

==>trim

移除字符串头尾空白。

1

2

3

4

5

// jQuery

$.trim(string);

 

// Native

string.trim();

==>map

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

1

2

3

4

5

6

7

// jQuery

$.map(array, (value, index) => {

});

 

// Native

array.map((value, index) => {

});

==>each

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

1

2

3

4

5

6

7

// jQuery

$.each(array, (index, value) => {

});

 

// Native

array.forEach((value, index) => {

});

==>grep

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

1

2

3

4

5

6

7

// jQuery

$.grep(array, (value, index) => {

});

 

// Native

array.filter((value, index) => {

});

==>type

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

1

2

3

4

5

6

7

8

9

10

// jQuery

$.type(obj);

 

// Native

function type(item) {

  const reTypeOf = /(?:^\[object\s(.*?)\]$)/;

  return Object.prototype.toString.call(item)

    .replace(reTypeOf, '$1')

    .toLowerCase();

}

==>merge

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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

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

1

2

3

4

5

// jQuery

$.now();

 

// Native

Date.now();

==>proxy

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

1

2

3

4

5

// jQuery

$.proxy(fn, context);

 

// Native

fn.bind(context);

==>makeArray

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

1

2

3

4

5

6

7

8

// jQuery

$.makeArray(arrayLike);

 

// Native

Array.prototype.slice.call(arrayLike);

 

// ES6-way

Array.from(arrayLike);

6.2 包含

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

1

2

3

4

5

// jQuery

$.contains(el, child);

 

// Native

el !== child && el.contains(child);

6.3 Globaleval

 全局执行 JavaScript 代码。

1

2

3

4

5

6

7

8

9

10

11

12

13

// 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 节点数组.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// 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 = document.location.href;

  context.head.appendChild(base);

 

  context.body.innerHTML = string;

  return context.body.children;

}

==>parseJSON

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

1

2

3

4

5

// 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 总会调用。

1

2

3

4

5

// jQuery

$promise.done(doneCallback).fail(failCallback).always(alwaysCallback)

 

// Native

promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)

7.2 when

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

1

2

3

4

5

6

// jQuery

$.when($promise1, $promise2).done((promise1Result, promise2Result) => {

});

 

// Native

Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});

7.3 Deferred

Deferred 是创建 promises 的一种方式。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

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

1

2

3

4

5

6

7

8

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

显示或隐藏元素。

1

2

3

4

5

6

7

8

9

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

1

2

3

4

5

6

7

8

9

10

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

调整元素透明度。

1

2

3

4

5

// jQuery

$el.fadeTo('slow',0.15);

// Native

el.style.transition = 'opacity 3s'// 假设 'slow' 等于 3 秒

el.style.opacity = '0.15';

8.5 FadeToggle

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

1

2

3

4

5

6

7

8

9

10

11

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

1

2

3

4

5

6

7

8

9

10

11

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

滑动切换显示或隐藏。

1

2

3

4

5

6

7

8

9

10

11

12

13

// 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 属性动画。

1

2

3

4

5

6

7

8

// jQuery

$el.animate({ params }, speed);

 

// Native

el.style.transition = 'all ' + speed;

Object.keys(params).forEach((key) =>

  el.style[key] = params[key];

)

  

 原文地址:https://github.com/nefe/You-Dont-Need-jQuery/blob/master/README.zh-CN.md

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery与原生JS相互转化 的相关文章

  • jenkins使用root账号

    1 修改配置文件 编辑配置文件 vim etc sysconfig jenkins 修改 JENKINS USER JENKINS USER root 2 修改相关文件夹为root权限 chown R root root var lib j
  • 数据仓库-数据分层理论详解

    主题 Subject 是在较高层次上将企业信息系统中的数据进行综合 归类和分析利用的一个抽象概念 每一个主题基本对应一个宏观的分析领域 在逻辑意义上 它是对应企业中某一宏观分析领域所涉及的分析对象 例如 销售分析 就是一个分析领域 因此这个
  • 蓝桥杯2017届C++B组省赛真题 分巧克力

    儿童节那天有K位小朋友到小明家做客 小明拿出了珍藏的巧克力招待小朋友们 小明一共有N块巧克力 其中第i块是Hi x Wi的方格组成的长方形 为了公平起见 小明需要从这 N 块巧克力中切出K块巧克力分给小朋友们 切出的巧克力需要满足 1 形状
  • 1、常用DOS命令大全

    一 DOS DiskOperatingSystem 磁盘操作系统 特点 单任务 单用户系统 使用命令行方式 控制计算机 二 DOS命令行的组成 1 DOS命令行中的基本概念 当前驱动器 当前盘 当前目录 相对路径 绝对路径 2 DOS命令的
  • 基于点云的3D障碍物检测

    基于点云的3D障碍物检测 主要有以下步骤 点云数据的处理 基于点云的障碍物分割 障碍物边框构建 点云到图像平面的投影 点云数据的处理 KITTI数据集 KITTI数据集有四个相机 主要使用第三个相机 序号为02 拍摄的图片 标定参数和标签文
  • I/O管理及监控命令

    一 磁盘原理 简单理解 1 盘片以每分钟数千转到上万转的速度在高速旋转 15K 10K 7 5K 5 2K RPM 2 磁头就能对盘片上的指定位置进行数据的读写操作 3 磁头磁化磁盘记录数据 4 从外到里存储 外快内慢 5 以扇区为单位存储
  • python-selenium-动作链拖拽;cookies处理

    1 动作链拖拽 导入动作链需要的包 from selenium webdriver import ActionChains 具体步骤 1 创建动作链对象 并绑定给浏览器 action ActionChains driver 2 点击并长按指
  • 停止IIS服务

    1 第一步 停止 World Wide Web Publishing Service 这个是W3C服务 2 第二部 停止 IIS Admin Service 这个IIS元数据管理服务 转载于 https www cnblogs com xi
  • 非接触IC卡中typeA卡和typeB卡的区别--总结,二者的调制方式和编码方式不同

    1 非接触式IC卡的国际规范ISO IEC14443的由来 在非接触式IC卡的发展过程中 这些问题逐渐被解决并形成通用的标准 体现在现在的射频IC卡的设计上 国际标准化组织 ISO 和国际电子技术委员会 IEC 为期制定了相应的非接触式IC
  • 虚拟主机的配置

    三种虚拟主机的配置 开启apache服务 编写环境变量 root localhost vim etc profile d httpd sh export PATH usr local apache bin PATH root localho
  • kettle表数据比较

    使用合并记录组件 我的kettle死活不能保存中文 唉 其中tab in 1和tab in 2代表两个数据源 合并记录 新旧数据源可随意指定 获取需要对比的字段 此处为了对比将比较记录先放在file中 identical 比较的所有字段相同
  • PPTP - GRE

    PPTP GRE PPTP Point to Point Tunneling Protocol 点对点隧道协议 GRE Generic Routing Encapsulation 通用路由封装 PPTP 的连接过程如下图 PPTP 可以用于
  • Python和Java读写文件的对比

    博主平时用Python比较多 最近因为工作需要使用Java编程 比较之下 发现Python读写文件真是太方便了 Java读写文件非常繁琐 简直让人抓狂 Python读写文件的语句 读文件 with open readFile r as in
  • 小程序实现毛玻璃的效果

    利用css的filter这个属性实现 在有弹框弹出的时候背景出现高斯模糊的效果 写个小例子记录一下 这个是背景是地图的情况下 做的处理 不管是文字还是图片什么的 在弹出框出来的时候给背景添加filter blur 20rpx 中间值的模糊程
  • Linux虚拟机sqlite数据库安装教程、命令实现sqlite

    参考 Linux虚拟机sqlite数据库安装教程 作者 图触靓 发布时间 2021 04 08 19 07 56 网址 https blog csdn net bhbhhyg article details 115528254 一 在官网下
  • Spark性能调优之广播变量

    一 背景 举例来说 虽然是举例 但是基本都是用我们实际在企业中用的生产环境中的配置和经验来说明的 50个executor 1000个task 一个map 10M 默认情况下 1000个task 1000份副本 10G的数据 网络传输 在集群
  • 帆软报表FineReport中数据连接之Tomcat配置JNDI连接

    1 问题描述 在帆软报表FineReport中 通过JNDI方式定义数据连接 首先在Tomcat服务器配置好JNDI 然后在设计器中直接调用JNDI的名字 即可成功使用JNDI连接 连接步骤如下 2 实现步骤 使用版本及环境 下面以Wind
  • 【ES6】Generator函数

    文章目录 一 声明Generator函数 二 调用 三 next 四 yield 五 return与yield区别 一 声明Generator函数 Generator函数 又称生成器函数 是ES6的一个重要的新特性 普通函数用functio
  • 魏副业而战:闲鱼推广显示设备异常怎么办

    我是魏哥 与其在家躺平 不如魏副业而战 今天是三八节 祝各位小姐姐们节日快乐 做网络项目 不免会遇到各种各样的问题 有人勇往直前 找方法 有人选择退缩 不同的选择 不同的结果 那么 遇到问题 我们应该怎么做呢 魏哥建议问度娘 一般情况下 我
  • VMWare Workstation 16 安装 Ubuntu 22.04 LTS

    最近想编译Android8 1 系统源码 不太想安装双系统 先尝试用虚拟机安装Ubuntu来编译试试 过程中也遇到一些特殊的错误 因此做了一次记录 VMWare Workstation 16 的下载和安装这里不作介绍 网上也有很多注册码可用

随机推荐

  • (Animator详解一)mixamo动画导入Unity的一些配置

    Mixamo是Adobe公司出品的免费动画库 可商用 软件分为characters 角色 Animations 动画 两个部分 下方的搜索框可以搜寻你想要的动作动画 网址为 Mixamo 搜索框的子菜单表示动画的类别 当我们的项目需要角色动
  • 【Xilinx Vivado时序分析/约束系列2】FPGA开发时序分析/约束-建立时间

    目录 基本概念 数据结束时间 Data finish time 保持时间门限 保持时间余量 Hold Slack 基本概念 数据结束时间 Data finish time 之前解释了数据达到的时间 对于data arrival time T
  • cpu矿工cpuminer-multi编译与使用

    文章目录 编译步骤 cpuminer multi 矿工运行 cpuminer multi有很多不同前辈开发 这里选用star最多且最流行的 lucasjones cpuminer multi 在编译中遇到了很多坑 这里全部整合到流程中 如果
  • nimg 文件服务器,NIMG-45. DEEP LEARNING-BASED PERITUMORAL MICROSTRUCTURE MAPPING IN GLIOBLASTOMAS USING FR...

    摘要 PURPOSE Characterization of the peritumoral microenvironment is a widely researched but as yet unsolved problem Deter
  • K-近邻算法预测电影类型

    K 近邻算法预测电影类型 k 近邻算法是一种比较简单 但是在一些方面又有很多作用的算法 比较常用的就是推荐入住位置 或者推荐入住酒店等等 K 近邻算法的原理 就是根据特征值 计算出离自己最近的那个分类 自己也属于那个类别 K 近邻是一种分类
  • 吴恩达机器学习(三) 无监督学习

    Unsupervised Learning Unsupervised learning allows us to approach problems with little or no idea what our results shoul
  • Django框架

    目录 目录 一 虚拟环境 1 什么是虚拟环境 2 作用 3 wondows下安装使用 二 Django框架 1 安装Django 2 拓展 虚拟机和虚拟环境问题 2 1虚拟机的三种网络模式 3 创建Django项目 3 1完整创建Djang
  • Python中Print()函数的用法___实例详解(全,例多)

    Python中Print 函数的用法 实例详解 全 例多 目 录 一 print 函数的语法 二 print 打印输出文本 三 print 中空格的使用方法 四 Print 换行 五 区隔符 sep 六 制表符 t 七 输出数学表达式 八
  • Qt:可视化UI设计

    1 创建项目 修改组件的对象名字和显示文本内容 创建一个 Widget Application 项目类 QDialog 在创建窗体时选择基类 QDialog 生成的类命名为 QWDialog 并选择生成窗体 在界面设计时 对需要访问的组件修
  • AES 配合mybaties 实现指定字段自动加解密

    1 加密工具类 Slf4j public class AESUtil 密钥长度 128 192 or 256 private static final int KEY SIZE 256 加密 解密算法名称 private static fi
  • C/C++从字符串中提取出数字的方法回顾

    在对格式化的数据进行处理的时候 很多时候需要在字符串中进行数据的提取 如果使用Oracle数据库 可以用里面的非常强大的sqlldr功能进行数据的提取和导入 在C C 中 可以自定义个方法提取出数字字符串 再使用atoi atof之类的方法
  • 颜色空间之RGB与YUV

    此篇是我在学习中做的归纳与总结 其中如果存在版权或知识错误或问题请直接联系我 欢迎留言 PS 本着知识共享的原则 此篇博客可以转载 但请标明出处 RGB CIE1931 RGB系统选择了700nm R 546 1nm G 435 8nm B
  • VGGNet实现CIFAR-100图像识别-1(数据预处理,one-hot)

    VGGNet CIFAR 100 导入数据 数据预处理 方法1 方法2 可能会遇到的问题 解决办法 Normalization和拆分训练集 验证集 One hot编码 未完待续 接下来请看另一篇博文 VGGNet实现CIFAR 100图像识
  • js复制功能插件

    JavaScript内容复制插件Clipboard js
  • 《C语言编程魔法书:基于C11标准》——1.3 主流C语言编译器介绍

    本节书摘来自华章计算机 C语言编程魔法书 基于C11标准 一书中的第1章 第1 3节 作者 陈轶 更多章节内容可以访问云栖社区 华章计算机 公众号查看 1 3 主流C语言编译器介绍 对于当前主流桌面操作系统而言 可使用Visual C GC
  • ARMV8体系结构简介:AArch64系统级体系结构之存储模型

    1 前言 关于存储系统体系架构 可以概述如下 存储系统体系结构的形式 VMSA 存储属性 2 存储系统体系结构 2 1 地址空间 指令地址空间溢出 指令地址计算 address of current instruction size of
  • Xcode14 终于放弃了bitcode和armv7架构,还有iOS 9、iOS 10

    相信大家已经了解到了不少关于Xcode 14的新消息 什么精简安装包 按需下载功能模块 提升编译速度 更快的xib storyBoard和SwiftUI app icon 1024像素图片 Xcode 14还放弃了一些东西 1 放弃了bit
  • openssl md5

    关于 16位和32位 md5得到的是一个16字节的散列值 每个字节用16进制 0x 格式成两个字符 连起来得到一个32个字符的串这就是所说的32位 16位就是取的32位的中间段 md5 aabbccdd 32位 bf3b2290e229da
  • (海伦公式)已知三角形三条边长,求面积

    海伦公式 已知三角形三条边长 求面积 海伦公式 S p p a p b p c 其中p是三角形的周长的一半p a b c 2 以下转自百度百科 海伦公式海又译作希伦公式 海龙公式 希罗公式 海伦 秦九韶公式 传说是古代的叙拉古国王 希伦 H
  • jQuery与原生JS相互转化

    前端发展很快 现代浏览器原生 API 已经足够好用 我们并不需要为了操作 DOM Event 等再学习一下 jQuery 的 API 同时由于 React Angular Vue 等框架的流行 直接操作 DOM 不再是好的模式 jQuery