tethys
v0.0.6
Published
mini dom library
Readme
tethys
这是一个微型的库,包含最常用的dom操作,压缩后只有4KB。
起源
自从 angular、vue 这类框架出现之后,我们终于不用再面对业务逻辑与dom操作混杂的代码。
但是,在极少的时候,特别是在组件中,我们仍然想要对页面元素进行直接的处理。
可是,你又不想仅仅为了用到几个方法,就去引入几十K的zepto或上百K的jquery。
这种情况下,tethys是一个不错的选择。
它包含以下实例方法:
和以下静态方法:
安装
如果在Node.js环境中使用,通过以下命令安装它。
npm i tethyshttps://www.npmjs.com/package/tethys
引用
标签引入:
<script src="https://raw.githubusercontent.com/hapjs/tethys/master/tethys.min.js"></script>如果通过script方式引入,你可以通过全局变量tethys来调用它。
如果全局变量$没有被其它库或者变量占用的话,那么$会指向tethys。
CommonJS/CMD/AMD引入:
var $ = require('tethys');ES6引入:
import $ from 'tethys';查找元素
通过选择器查找
$('#id');
$('.class');直接传入元素
$(document.body);指定查找范围
$('style', document.head);与jQuery类似,你将得到一个包含查找到的节点的数组,这个数组有下列方法供你操作:
find
查找子元素
$('head').find('script'); // 查找<head>中的所有<script>each
遍历
$('script').each(function(script, index){
// console.log(this.getAttribute('type'));
});on
事件绑定
$('button').on('click', function(){
// this.style.color = 'red';
});trigger
触发元素上绑定的事件监听函数
$('button').trigger('click');可以触发的事件包括:
focus
blur
select
change和所有鼠标事件:
mousedown
mouseup
mousemove
click
dblclick
mouseover
mouseout
mouseenter
mouseleave
contextmenucss
查询实际样式(computedStyle)
$('button').css('color'); // red设置样式
$('button').css('color', 'red');
$('button').css({
display: 'block',
border: '1px solid green'
});style
查询内联样式,如果没有内联样式,返回空字符串
$('button').style('color');width
设置或查询宽度,参数或返回值均不带单位且是数值类型
$('button').width();
$('button').width(200);height
设置或查询高度,参数或返回值均不带单位且是数值类型
$('button').height();
$('button').height(200);attr
设置单个属性
$('button').attr('maxlength', 16);设置多个属性
$('button').attr({
'maxlength': 16
});取属性:
$('button').attr('maxlength'); // 16class
添加class
$('button').addClass('active');删除class
$('button').removeClass('active');判断是否存在指定class
$('button').hasClass('active'); // trueshow/hide
显示
$('button').show();隐藏
$('button').hide();html
修改文档的innerHTML
$('button').html('<p>Hello world!</p>');append
追加子元素
$('button').append('<p>Hello world!</p>');delay
延时执行一个函数
$('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
浅层复制
$.extend(obj1, obj2);
$.extend(obj1, obj2, obj3);深层复制
$.extend(true, obj1, obj2)