jQuery 原生javasricpt 比较
Creating Elements
// jQuery
$('<div></div>');
// native
document.createElement('div');
选择器查询
// jQuery
$('selector');
$('.class');
$('#id');
$('a[target=_blank]');
// Native
document.querySelectorAll('selector');
document.getElementsByClassName('class');
document.getElementById('id');
document.querySelectorAll('a[target=_blank]');
兄弟元素
// 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;
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);
获取属性
// 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');
Get style
// jQuery
$el.css("color");
// Native
// 注意:此处为了解决当 style 值为 auto 时,返回 auto 的问题
const win = el.ownerDocument.defaultView;
```// null 的意思是不返回伪类元素
## native
```js
function getStyle(elem, property) {
// ie (currentStyle) , other browsers (getComputedStyle)
return window.getComputedStyle ? window.getComputedStyle(elem, false)[property] : elem.currentStyle[property];
// 或 (element.currentStyle || window.getComputedStyle(element, null))[property]
}
Set style
// jQuery
$el.css({ color: "#ff0011" });
// Native
el.style.color = '#ff0011';
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);
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;
获得匹配元素相对父元素的偏移
// jQuery
$el.position();
// Native
{ left: el.offsetLeft, top: el.offsetTop }
获得匹配元素相对文档的偏移
// 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
}
}
获取元素滚动条垂直位置
// jQuery
$(window).scrollTop();
// Native
(document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
从 DOM 中移除元素
// jQuery
$el.remove();
// Native
el.parentNode.removeChild(el);
返回指定元素及其后代的文本内容。
// jQuery
$el.text();
// Native
el.textContent;
设置元素的文本内容。
// jQuery
$el.text(string);
// Native
el.textContent = string;
Get HTML
// jQuery
$el.html();
// Native
el.innerHTML;
Set HTML
// jQuery
$el.html(htmlString);
// Native
el.innerHTML = htmlString;
移除所有子节点
//jQuery
$el.empty();
//Native
el.innerHTML = '';
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);
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);
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);
}
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);
}
深拷贝被选元素
//jQuery
$el.clone();
//Native
el.cloneNode();
//深拷贝添加参数‘true’
ready
// jQuery
$(document).ready(eventHandler);
// Native
// 检测 DOMContentLoaded 是否已完成
if (document.readyState === 'complete' || document.readyState !== 'loading') {
eventHandler();
} else {
document.addEventListener('DOMContentLoaded', eventHandler);
}
event on
// jQuery
$el.on(eventName, eventHandler);
// Native
el.addEventListener(eventName, eventHandler);
event off
// jQuery
$el.off(eventName, eventHandler);
// Native
el.removeEventListener(eventName, eventHandler);
isNumeric
// jQuery
$.isNumeric(item);
// Native
function isNumeric(value) {
var type = typeof value;
return (type === 'number' || type === 'string') && !Number.isNaN(value - Number.parseFloat(value));
}
isFunction
// 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;
}
extend
// jQuery
$.extend({}, defaultOpts, opts);
// Native
Object.assign({}, defaultOpts, opts);
each
// jQuery
$.each(array, (index, value) => {});
// Native
array.forEach((value, index) => {});
type
// jQuery
$.type(obj);
// Native
function type(item) {
const reTypeOf = /(?:^\[object\s(.*?)\]$)/;
return Object.prototype.toString.call(item).replace(reTypeOf, '$1').toLowerCase();
}
show hide
// jQuery
$el.show();
$el.hide();
// Native
el.style.display = '' | 'inline' | 'inline-block' | 'inline-table' | 'block';
el.style.display = 'none';
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';
}
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';
FadeTo
// jQuery
$el.fadeTo('slow', 0.15);
// Native
el.style.transition = 'opacity 3s'; // 假设 'slow' 等于 3 秒
el.style.opacity = '0.15';
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;
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';
}
执行一系列 CSS 属性动画
// jQuery
$el.animate({ params }, speed);
// Native
el.style.transition = 'all ' + speed;
Object.keys(params).forEach((key) =>
el.style[key] = params[key];
)
原文地址
个人博客 - 前端入门
BAT前端面试题目总结