jquery和原生相互转换,脱离jquery不用愁

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前端面试题目总结

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容