前言
看一波 You Might Not Need JQUERY
整理一些常用的 顺便同时複习 JS 和 JQ
大纲
通用选择器DOM选择器取得 HTML, 属性, Style, TextCSS Class操作CSS 位置、大小 (取得/设定)Effect (show/fade/fadeIn)DOM 操作 (判断)DOM 操作 (删除/改变/複製)DOM 操作 (建立/插入/顺序)insertAdjacentHTML (DOM插入万金油)DOM 操作 (迴圈执行)Events (事件监听、ready、自定义事件)Array 阵列相关 (each, map, inArray, isArray)Utils 功能型 (Date(), ParseJSON, trim())AJAX (JSON, POST, Request)通用选择器
JQ 选择器才可使用 JQ方法,勿混用JQ 可一次多选多个子元素并作处理JS 使用doqsAll 需要迴圈去套用样式、设置监听或事件代理处理 // JS document.querySelector('.') document.querySelectorAll('.') //JQ $('.test')
DOM选择器
JQ限定 找首 $(el).first()找父找子找兄弟 // 找父 $(el).parent(); el.parentNode // JQ 找子,只找下一层 $(el).children() // 回传 NodeList 可先 Array.From() 转成阵列 el.children // 找子/后代 $(el).find('li'); el.querySelectorAll('li'); // JQ 限定 $(el).first() // 找兄弟 $(el).siblings(); Array.prototype.filter.call(el.parentNode.children, function(child){ return child !== el; }); // 找上、下个兄弟节点 $(el).prev(); $(el).next(); el.nextElementSibling el.previousElementSibling
取得 HTML, 属性, Style, Text
HTML, 属性, Style, Text
// 设定 DOM 内容 $(el).html(string) el.innerHTML = string // 取得 HTML $(el).html() el.innerHTML // 取得 Outer HTML (包含自己) $('<div>').append($(el).clone()).html(); el.outerHTML // 取得属性 $(el).attr('color'); el.getAttribute('color'); // 设定属性 $(el).attr('tabindex', 3); el.setAttribute('tabindex', 3); // 取得Style 用-而非驼峰 $(el).css('background-color') getComputedStyle(el)['background-color']; // 设定Style $(el).css('border-width', '20px'); // 最好使用Class el.style.borderWidth = '20px'; // 取得文字 $(el).text(); el.textContent // 设定文字 $(el).text(string); el.textContent = string;
CSS Class操作
IE9- 无法使用ClassList,相容写法整理在下 // JS el.classList.add('show') el.classList.remove('show') el.classList.toggle('show') el.classList.contains('show') $(el).addClass('show') $(el).removeClass('show') $(el).toggleClass('show') $(el).hasClass('show')
// JS Add Class (IE8 写法) if(el.classList) { el.classList.add(className) } else { el.className += ' ' + className } // Has Class (IE8 写法) $(el).hasClass(className); if (el.classList) { el.classList.contains(className); } else { new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className) } // Remove Class (IE8 写法) if (el.classList) { el.classList.remove(className); } else { el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } // Toggle Class (IE9+ 写法) if (el.classList) { el.classList.toggle(className); } else { var classes = el.className.split(' '); var existingIndex = classes.indexOf(className); if (existingIndex >= 0) classes.splice(existingIndex, 1); else classes.push(className); el.className = classes.join(' '); }
CSS 位置、大小 (取得/设定)
scrollTop [元素顶端和ViewPort最顶端之间的距离]getBoundingClientRect() [Viewport 的 相对位置]getComputedStyle() [计算运算后的元素各Style]上面几个有空会写一篇文整理一波
// 取得位置 $(el).position(); {left: el.offsetLeft, top: el.offsetTop} // Viewport 的 相对位置 var offset = el.offset(); { top: offset.top - document.body.scrollTop, left: offset.left - document.body.scrollLeft } // JS el.getBoundingClientRect() // Outer Height $(el).outerHeight(); el.offsetHeight // Outer Height + Margin $(el).outerHeight(true); function outerHeight(el) { var height = el.offsetHeight; var style = getComputedStyle(el); height += parseInt(style.marginTop) + parseInt(style.marginBottom); return height; } outerHeight(el); // Outer Width $(el).outerWidth() el.offsetWidth // Outer Width + Margin 可与 上面的合併用带入参数判断 $(el).outerWidth(true); function outerWidth(el) { var width = el.offsetWidth; var style = getComputedStyle(el); width += parseInt(style.marginLeft) + parseInt(style.marginRight); return width; } outerWidth(el); // Offset $(el).offset(); var rect = el.getBoundingClientRect(); { top: rect.top + document.body.scrollTop, left: rect.left + document.body.scrollLeft } // Offset Parent $(el).offsetParent(); el.offsetParent || el
Effect (show/fade/fadeIn)
show / fadefadeIn 原生写法不是很懂动画可用 animate.css + js 去给 Class 实现 $(el).show() $(el).hide() el.style.display = '' el.style.display = 'none' $(el).fadeIn() function fadeIn(el) { el.style.opacity = 0 var last = +new Date() var tick = function() { el.style.opacity = +el.style.opacity + (new Date() - last) / 400 last = +new Date() if (+el.style.opacity < 1) { (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16) } } tick() } fadeIn(el)
DOM 操作 (删除/改变/複製)
cloneNode 参数 true:深拷贝(含子) false:浅拷贝 (仅複製自身)複製后 还是要做插入的动作使用 clone 要注意是否会造成 一样的ID 切记!! // 删除子元素 $(el).remove(); // JS Old el.parentNode.removeChild(el); // JS IE 不支援 el.remove() // 用 OO 取代自身 $(el).replaceWith(string); el.outerHTML = string; // 複製节点 $(el).clone(); el.cloneNode(true); // 清空父元素之下 $(el).empty() el.innerHTML = ''
DOM 操作 (判断)
判断节点是否符合判断节点是否符合选择器判断子是否存在判断子是否为其子元素 // 判断节点是否符合 $(el).is($(otherEl)); el === otherEl if (e.target.classList.contains('')) { } if (e.target.tagName.toLowerCase() === 'a') {} // 判断节点是否符合选择器 $(el).is('.my-class'); var matches = function(el, selector) { return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector); }; matches(el, '.my-class'); // 判断子是否存在 $(el).find(selector).length; el.querySelector(selector) !== null // 判断子是否为其子元素 $.contains(el, child); if((el !== child) && el.contains(child))
DOM 操作 (建立/插入/顺序)
insertAdjacentHTML DOM插入万金油JS creatElement('p')JS prepend / append (同JQ写法,但IE不支援)prepend / append 若元素存在,会进行移动JS appendChild / insertBefore (IE支援版) // JS 建立元素 document.creatElement('p') // 插入前 $(parent).prepend(el); // JS OLD parent.insertBefore(el, parent.firstChild); // JS IE不支援 el.prepend() // 插入父元素下 $(parent).append(el); // JS OLD parent.appendChild(el); // JS IE不支援 el.append() // 插入其前、后 $(el).after(htmlString) $(el).before(htmlString)
insertAdjacentHTML (DOM插入万金油)
动作有四种(设定position参数)beforebegin: 加在 elem 之前afterbegin: 加在 elem 里面,首个子元素之前beforeend: 加在 elem 里面,末个子元素之后afterend: 加在 elem 之后 el.insertAdjacentHTML( position , htmlString)
DOM 操作 (迴圈执行)
// 迴圈执行 $(selector).each(function(i, el){ }); const elements = document.querySelectorAll(selector); Array.prototype.forEach.call(elements, function(el, i){ }); // 符合的元素才执行 $(selector).filter(filterFn) Array.prototype.filter.call(document.querySelectorAll(selector), filterFn)
Events
on off 事件监听 挂载 & 移除自定义事件 没用过 (求放过...)关键字搜寻 Trigger Custom / Trigger Native
// on off 事件监听 $(el).on('click', Func) el.addEventListener('click', Func) $(el).off('click', Func) el.removeEventListener('click', Func) // Ready $(document).ready(function(){ }) // 作者 ready function ready(fn) { if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){ fn() } else { document.addEventListener('DOMContentLoaded', fn) } } // 个人写法 ;(function () { document.addEventListener('DOMContentLoaded', () => {}) }())
Array 阵列相关
forEach / filter / map$.grep 等同 ES6 FilterinArray 找 Array 内的内容isArray 判断是否为阵列LearnMore 可以看看我撰写的其他篇阵列整理 // 判断是否为阵列 $.isArray(arr) Array.isArray(arr) $.each(arr, function(i, item){ }) arr.forEach(function(item, i){ }) $.map(arr, function(value, index){ }) arr.map(function(value, index){ }) // 找项目 $.inArray(item, arr) // indexOf 回传-1表找不到 arr.indexOf(item)
Utils 功能型
时间 NowParse JSONtrim 字串去除前后的空白P.S. 其他看不是很懂 待补.....
Bind, Deep Extend, Extend, Parse Html, Type
// 时间 Now $.now() Date.now() // Parse JSON $.parseJSON(string) JSON.parse(string) // Trim $.trim(string) string.trim()
AJAX
原生 JS 用 XMLHttpRequest 支援度最高推荐使用 axios // JS XHR 範例 getData('https://jsonplaceholder.typicode.com/users') function getData(url) { const xhr = new XMLHttpRequest() xhr.open('GET', url, true) // onreadystatechange & onload 则一即可 xhr.onload = function () { if (xhr.status === 200) { console.log(this.responseText) } } xhr.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.table(JSON.parse(this.responseText)) } else if (this.status === 404) { console.log('Not Found') } } xhr.onerror = function () { console.log('Request Error...') } xhr.send() }
// JSON $.getJSON('/my/url', function(data) { }) // JS 使用 XHR // POST $.ajax({ type: 'POST', url: '/my/url', data: data }) // JS XHR const request = new XMLHttpRequest() request.open('POST', '/my/url', true) request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded charset=UTF-8') request.send(data) // Request $.ajax({ type: 'GET', url: '/my/url', success: function(resp) { }, error: function() { } }); // JS 使用 XHR
参考资料
YOU MIGHT NOT NEED JQUERY
jQuery Cheat Sheet