tethysDOM 操作庫(kù)
tethys,這是一個(gè)微型的庫(kù),包含最常用的 DOM 操作,壓縮后只有 2KB。
起源
自從 angular、vue 這類框架出現(xiàn)之后,我們終于不用再面對(duì)業(yè)務(wù)邏輯與dom操作混雜的代碼。
但是,在極少的時(shí)候,特別是在組件中,我們?nèi)匀幌胍獙?duì)頁(yè)面元素進(jìn)行直接的處理。
可是,你又不想僅僅為了用到幾個(gè)方法,就去引入幾十K的zepto或上百K的jquery。
這種情況下,tethys是一個(gè)不錯(cuò)的選擇。
它包含以下實(shí)例方法:
和以下靜態(tài)方法:
安裝
如果在Node.js環(huán)境中使用,通過以下命令安裝它。
npm i tethys
https://www.npmjs.com/package/tethys
引用
標(biāo)簽引入:
<script src="https://raw.githubusercontent.com/hapjs/tethys/master/tethys.min.js"></script>
如果通過 script 方式引入,你可以通過全局變量 tethys 來調(diào)用它。
如果全局變量$沒有被其它庫(kù)或者變量占用的話,那么$會(huì)指向tethys。
CommonJS/CMD/AMD引入:
var $ = require('tethys');
ES6引入:
import $ from 'tethys';
查找元素
通過選擇器查找
$('#id'); $('.class');
直接傳入元素
$(document.body);
指定查找范圍
$('style', document.head);
與 jQuery 類似,你將得到一個(gè)包含查找到的節(jié)點(diǎn)的數(shù)組,這個(gè)數(shù)組有下列方法供你操作:
each
遍歷
$('script').each(function(script, index){ // console.log(this.getAttribute('type')); });
on
事件綁定
$('button').on('click', function(){ // this.style.color = 'red'; });
css
設(shè)置單個(gè)樣式
$('button').css('color', 'red');
設(shè)置多個(gè)樣式
$('button').css({
display: 'block',
border: '1px solid green' });
取樣式
$('button').css('color'); // red
attr
設(shè)置單個(gè)屬性
$('button').attr('maxlength', 16);
設(shè)置多個(gè)屬性
$('button').attr({ 'maxlength': 16 });
取屬性:
$('button').attr('maxlength'); // 16
class
添加class
$('button').addClass('active');
刪除class
$('button').removeClass('active');
判斷是否存在指定class
$('button').hasClass('active'); // true
show/hide
顯示
$('button').show();
隱藏
$('button').hide();
html
修改文檔的innerHTML
$('button').html('<p>Hello world!</p>');
鏈?zhǔn)秸{(diào)用
$('button')
.css('color', 'red')
.addClass('active')
.each(function(){ })
.on('click', function(){ });
獲得原生節(jié)點(diǎn)
栗子1:獲得第一個(gè)script標(biāo)簽
$('script')[0]; // <script>...</script>
栗子2:遍歷所有style標(biāo)簽
$('style').each(function(){ // <style>...</style> })
靜態(tài)方法
除了上述實(shí)例方法以外,還有下面的靜態(tài)方法可以使用。
extend
淺層復(fù)制
$.extend(obj1, obj2); $.extend(obj1, obj2, obj3);
深層復(fù)制
$.extend(true, obj1, obj2)
