WebApp开发-Zepto
- 作者: Life76339438
- 来源: 51数据库
- 2021-07-29
zepto.js自己去官网下载哈。
dom操作
$(document).ready(function(){
var $cr = $("<div class='cr'>插入的div</div>");
// 插入操作
$("#a").append($cr);
$cr.appendto($("#a"));
$("#a").prepend($cr);
$cr.prependto($("#a"));
$("#a").after($cr);
$cr.insertafter($("#a"));
$("#a").before($cr);
$cr.insertbefore($("#a"));
// 删除 remove\empty
$("ul li").remove();
$("ul li").empty();
// 复制节点
$("ul li").click(function(){
$(this).clone().appendto("ul");
});
// 替换节点 replacewith
$("p").replacewith("<span>是的,哈哈</span>");
// 包裹节点 wrap wrapall
$("p").wrap("<div></div>");
$("p").wrapall("<div></div>");
});
属性与样式操作
$(document).ready(function(){
// 属性操作 attr("title") attr("name","att") attr({"name":"att" , "class":"test"}) removeattr("title name")
console.log($("div").attr("title"));
$("div").attr("name","att");
$("div").attr({"name":"att" , "class":"test"})
$("div").removeattr("title name");
// 添加样式操作 addclass
$("div").addclass("red").addclass("fs");
$("div").addclass("red fs");
// 删除class类 removeclass
$("div").removeclass();
// 切换样式 toggle toggleclass
$("button").click(function(){
$("div").toggle(); // show和hide的切换
$("div").toggleclass("red"); // addclass("red")和removeclass("red");
});
// 判断是否含有某个样式 hasclass
console.log($("div").hasclass("red fs"))
});
遍历节点
$(document).ready(function(){
// next是取得紧邻的后面的同辈元素
console.log($("#one h3").next());
// prev获取紧邻的前面的同辈元素
console.log($("#one a").prev());
// siblings获取前后的所有同辈元素
console.log($("#one p").siblings());
// parent与parents直系亲属
console.log($("b").parent());
console.log($("b").parents());
});
css-dom操作
$(document).ready(function(){
$(".one").css("color", "red").css("fontsize", "36px");
$(".one").css({
color:"red",
fontsize:"36px"
});
$(".one").width(500);
$(".one").height(500);
});
ready与onload的区别
// html文件 、 css文件 、 js文件 、 图片文件等
$(document).ready(function(){
// dom加载完毕,图片并未完全加载,调用时机比较快
});
window.onload = function(){
// 全部文件加载完毕,调用时机比较久
}
事件开头简写
$(document).ready(function(){
})
$(function(){
})
$().ready(function(){
})
事件绑定
$(".one").bind("click", function(e){
console.log("one被点击了!!!")
})
$(".one").click(function(e){
console.log("我是简写方式");
})
$(".one").on("click", function(e){
console.log("我是on事件");
});
---------------------------------
// on
$("ul").on('click', 'li', function(e){
})
// off
$("li").off();
zepto不支持事件捕获
事件其他用法
// 自定义事件
$("div").bind("muke", function(){
console.log("触发自定义事件");
});
$("div").trigger("muke");
// 命名空间
$("div").bind("click", function(){
console.log("我是普通的click事件");
})
$("div").bind("click.muke", function(){
console.log("我是click.muke的事件");
})
$("div").unbind(".muke");
// 绑定多个事件
$("div").bind("click", function(){
console.log(111)
}).bind("touchstart", function(){
console.log(222)
})
动画
$('button').on('click' , function(){
$('div').toggle('slow'); //切换元素的显示与隐藏
$('div').hide(3000);
$('div').show('slow');
$('div').fadein('slow');
$('div').fadeout('slow');
$('div, button').fadetoggle('slow');
$("div").fadeto(3000 , 1)
})
animate() 动画函数
$("div").animate({left:"300px", height:"300px"}, 3000, function(){
alert("动画执行完毕");
})
ajax
function ajax(){
var xmlhttpreq = null;
if(window.activexobject){
// 兼容ie5、ie6
xmlhttpreq = new activexobject("microsoft.xmlhttp");
}else{
xmlhttpreq = new xmlhttprequest();
}
xmlhttpreq.open("get", "test.php", true);
xmlhttpreq.onreadystatechange = requestcallback;
function requestcallback(){
if(xmlhttpreq.readystate == 4){
if(xmlhttpreq.status == 200){
console.log("获取数据:"+xmlhttpreq.responsetext);
}
}
}
xmlhttpreq.send(null);
}
ajax请求
// get
$.get('urlxxx',function(response){
$(document.body).append(response)
});
// post
$.post('urlxxx', { sample: 'payload' }, function(response){
});
// ajax
$.ajax({
type: 'get',
url: 'urlxxx',
data: { name: 'zepto.js' },
datatype: 'json',
success: function(data){
this.append(data.project.html)
},
error: function(xhr, type){
alert('ajax error!')
}
})
touch模块
先引入touch.js
<script type="text/javascript" src="../../lib/touch.js"></script>
touch.js
;(function($){
var touch = {},
touchtimeout, taptimeout, swipetimeout, longtaptimeout,
longtapdelay = 750,
gesture
function swipedirection(x1, x2, y1, y2) {
return math.abs(x1 - x2) >=
math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'left' : 'right') : (y1 - y2 > 0 ? 'up' : 'down')
}
function longtap() {
longtaptimeout = null
if (touch.last) {
touch.el.trigger('longtap')
touch = {}
}
}
function cancellongtap() {
if (longtaptimeout) cleartimeout(longtaptimeout)
longtaptimeout = null
}
function cancelall() {
if (touchtimeout) cleartimeout(touchtimeout)
if (taptimeout) cleartimeout(taptimeout)
if (swipetimeout) cleartimeout(swipetimeout)
if (longtaptimeout) cleartimeout(longtaptimeout)
touchtimeout = taptimeout = swipetimeout = longtaptimeout = null
touch = {}
}
function isprimarytouch(event){
return (event.pointertype == 'touch' ||
event.pointertype == event.mspointer_type_touch)
&& event.isprimary
}
function ispointereventtype(e, type){
return (e.type == 'pointer'+type ||
e.type.tolowercase() == 'mspointer'+type)
}
$(document).ready(function(){
var now, delta, deltax = 0, deltay = 0, firsttouch, _ispointertype
if ('msgesture' in window) {
gesture = new msgesture()
gesture.target = document.body
}
$(document)
.bind('msgestureend', function(e){
var swipedirectionfromvelocity =
e.velocityx > 1 ? 'right' : e.velocityx < -1 ? 'left' : e.velocityy > 1 ? 'down' : e.velocityy < -1 ? 'up' : null
if (swipedirectionfromvelocity) {
touch.el.trigger('swipe')
touch.el.trigger('swipe'+ swipedirectionfromvelocity)
}
})
.on('touchstart mspointerdown pointerdown', function(e){
if((_ispointertype = ispointereventtype(e, 'down')) &&
!isprimarytouch(e)) return
firsttouch = _ispointertype ? e : e.touches[0]
if (e.touches && e.touches.length === 1 && touch.x2) {
// clear out touch movement data if we have it sticking around
// this can occur if touchcancel doesn't fire due to preventdefault, etc.
touch.x2 = undefined
touch.y2 = undefined
}
now = date.now()
delta = now - (touch.last || now)
touch.el = $('tagname' in firsttouch.target ?
firsttouch.target : firsttouch.target.parentnode)
touchtimeout && cleartimeout(touchtimeout)
touch.x1 = firsttouch.pagex
touch.y1 = firsttouch.pagey
if (delta > 0 && delta <= 250) touch.isdoubletap = true
touch.last = now
longtaptimeout = settimeout(longtap, longtapdelay)
// adds the current touch contact for ie gesture recognition
if (gesture && _ispointertype) gesture.addpointer(e.pointerid)
})
.on('touchmove mspointermove pointermove', function(e){
if((_ispointertype = ispointereventtype(e, 'move')) &&
!isprimarytouch(e)) return
firsttouch = _ispointertype ? e : e.touches[0]
cancellongtap()
touch.x2 = firsttouch.pagex
touch.y2 = firsttouch.pagey
deltax += math.abs(touch.x1 - touch.x2)
deltay += math.abs(touch.y1 - touch.y2)
})
.on('touchend mspointerup pointerup', function(e){
if((_ispointertype = ispointereventtype(e, 'up')) &&
!isprimarytouch(e)) return
cancellongtap()
// swipe
if ((touch.x2 && math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && math.abs(touch.y1 - touch.y2) > 30))
swipetimeout = settimeout(function() {
if (touch.el){
touch.el.trigger('swipe')
touch.el.trigger('swipe' + (swipedirection(touch.x1, touch.x2, touch.y1, touch.y2)))
}
touch = {}
}, 0)
// normal tap
else if ('last' in touch)
// don't fire tap when delta position changed by more than 30 pixels,
// for instance when moving to a point and back to origin
if (deltax < 30 && deltay < 30) {
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
taptimeout = settimeout(function() {
// trigger universal 'tap' with the option to canceltouch()
// (canceltouch cancels processing of single vs double taps for faster 'tap' response)
var event = $.event('tap')
event.canceltouch = cancelall
// [by paper] fix -> "typeerror: 'undefined' is not an object (evaluating 'touch.el.trigger'), when double tap
if (touch.el) touch.el.trigger(event)
// trigger double tap immediately
if (touch.isdoubletap) {
if (touch.el) touch.el.trigger('doubletap')
touch = {}
}
// trigger single tap after 250ms of inactivity
else {
touchtimeout = settimeout(function(){
touchtimeout = null
if (touch.el) touch.el.trigger('singletap')
touch = {}
}, 250)
}
}, 0)
} else {
touch = {}
}
deltax = deltay = 0
})
// when the browser window loses focus,
// for example when a modal dialog is shown,
// cancel all ongoing events
.on('touchcancel mspointercancel pointercancel', cancelall)
// scrolling the window indicates intention of the user
// to scroll, not tap or swipe, so cancel all ongoing events
$(window).on('scroll', cancelall)
})
;['swipe', 'swipeleft', 'swiperight', 'swipeup', 'swipedown',
'doubletap', 'tap', 'singletap', 'longtap'].foreach(function(eventname){
$.fn[eventname] = function(callback){ return this.on(eventname, callback) }
})
})(zepto)
使用时:
<script>
$(document).ready(function(){
$('#touch_test').bind('touchmove', function(e) { e.preventdefault() })
listen_to('#touch_test')
function listen_to(el) {
$(el).tap(function(){
console.log(' | tap!')
})
.doubletap(function(){
console.log(' | double tap!')
})
.swipe(function(){
console.log(' | swipe!')
})
.swipeleft(function(){
console.log(' | swipe left!')
})
.swiperight(function(){
console.log(' | swipe right!')
})
.swipeup(function(){
console.log(' | swipe up!')
})
.swipedown(function(){
console.log(' | swipe down!')
})
.longtap(function(){
console.log(' | long tap!')
})
.singletap(function(){
console.log(' | single tap!')
})
}
});
</script>
插件的写法
先编写自定义插件js文件
zepto.color.js
;(function($){
//一个插件的写法
$.fn.color = function(option){
var options = $.extend({
col: "blue",
fz : "20px"
}, option);
this.css("color", options.col);
this.css("fontsize", options.fz);
return this;
}
})(zepto);
//多组插件写法
/*
;(function($){
$.extend($.fn, {
color: function(option){
var options = $.extend({
col: "blue",
fz : "20px"
}, option);
this.css("color", options.col);
this.css("fontsize", options.fz);
return this;
},
background: function(option){
var options = $.extend({
bg: "blue"
}, option);
this.css("background", options.bg);
return this;
}
})
})(zepto);
*/
使用时:
<script type="text/javascript" src="../../lib/zepto.color.js"></script>
<script type="text/javascript">
$("div").color({
col : "red"
}).addclass("helloworld");
</script>
推荐阅读
