轻量级 DOM 操作库
- find
- each
- on
- trigger
- css
- style
- width
- height
- attr
- hasClass
- addClass
- removeClass
- show
- hide
- html
- append
- delay
如果在Node.js环境中使用,通过以下命令安装它。
npm i tethys
https://www.npmjs.com/package/tethys
<script src="https://raw.githubusercontent.com/hapjs/tethys/master/tethys.min.js"></script>
如果通过script方式引入,你可以通过全局变量tethys
来调用它。
如果全局变量$
没有被其它库或者变量占用的话,那么$
会指向tethys
。
var $ = require('tethys');
import $ from 'tethys';
通过选择器查找
$('#id');
$('.class');
直接传入元素
$(document.body);
指定查找范围
$('style', document.head);
与jQuery类似,你将得到一个包含查找到的节点的数组,这个数组有下列方法供你操作:
查找子元素
$('head').find('script'); // 查找<head>中的所有<script>
遍历
$('script').each(function(script, index){
// console.log(this.getAttribute('type'));
});
事件绑定
$('button').on('click', function(){
// this.style.color = 'red';
});
触发元素上绑定的事件监听函数
$('button').trigger('click');
可以触发的事件包括:
focus
blur
select
change
和所有鼠标事件:
mousedown
mouseup
mousemove
click
dblclick
mouseover
mouseout
mouseenter
mouseleave
contextmenu
查询实际样式(computedStyle)
$('button').css('color'); // red
设置样式
$('button').css('color', 'red');
$('button').css({
display: 'block',
border: '1px solid green'
});
查询内联样式,如果没有内联样式,返回空字符串
$('button').style('color');
设置或查询宽度,参数或返回值均不带单位且是数值类型
$('button').width();
$('button').width(200);
设置或查询高度,参数或返回值均不带单位且是数值类型
$('button').height();
$('button').height(200);
设置单个属性
$('button').attr('maxlength', 16);
设置多个属性
$('button').attr({
'maxlength': 16
});
取属性:
$('button').attr('maxlength'); // 16
添加class
$('button').addClass('active');
删除class
$('button').removeClass('active');
判断是否存在指定class
$('button').hasClass('active'); // true
显示
$('button').show();
隐藏
$('button').hide();
修改文档的innerHTML
$('button').html('<p>Hello world!</p>');
追加子元素
$('button').append('<p>Hello world!</p>');
延时执行一个函数
$('button').addClass('fade-out').delay(1000, function(){
this.hide();
});
$('button')
.css('color', 'red')
.addClass('active')
.each(function(){ })
.on('click', function(){ });
栗子1:获得第一个script标签
$('script')[0]; // <script>...</script>
栗子2:遍历所有style标签
$('style').each(function(){
// <style>...</style>
})
除了上述实例方法以外,还有下面的静态方法可以使用。
浅层复制
$.extend(obj1, obj2);
$.extend(obj1, obj2, obj3);
深层复制
$.extend(true, obj1, obj2)