1.什么是juery
jquery是一个javascript库,它通过封装原生的javascript函数得到一整套定义好的方法,集成了javascript,css,Dom,和ajax
DOM:Document Object Model,简称DOM
2.第一个helloworld
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>基础核心</title>
<script type="text/javascript" src="tool.js"></script>
<script type="text/javascript" src="base.js"></script>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
</head>
<body>
<div id="box">基础核心</div>
</body>
</html>
demo.js
/*
$(function () { //匿名函数
$('#box').css('color', 'red'); //对页面元素的选择,通过id来选择,加#,$()是一种选择器,是 //jquery对象的缩写形式($===jQuery),包装器,.css是内置功 // //能函数,$符号返回的是juery对象的内部方法,用alert($)查看如下图:
//$必须包含一个东西,哪怕是空的$()返回的是[object,object],这就是juery对象
});
$(function () {
/*
①//alert($); //jQuery对象的内部
②alert($()); //返回的jQuery对象
③alert($('#box')); //返回的也是jQuery对象
④alert($('#box').css('color', 'red')); //还是返回的jQuery对象
$('#box').css('color', 'red').css('font-size', '200px').css('font-weight', 'bold'); //支持链式编程,最终返回的还是juery对象
});
*/
3.关于为什么使用$(function () {});这种包裹方式
解释:因为juery要操作html中的元素,就要知道这些元素的存在,html是顺序加载的,$(document).ready()是对html中的元素进行预加载,$(function(){})是对上述形式的简写,只有html预加载完成以后,被包裹的逻辑才会执行,被包裹的内容延时加载,window.load因为加载比较慢可能会出现假死状态,而$(doucument).ready()只加载document的元素,比较快
4.用juery得到html的DOM对象(做到了juery和dom之间进行互换)
demo.js
$(function () {
//alert(document.getElementById('box')); //[object HTMLDivElement],原生得到DOM对象的方法
//alert($('#box').get(0)); //使用juery得到Dom的方法[object HTMLDivElement]
//alert($(document.getElementById('box')).css('color', 'red')); //jQuery对象和DOM对象之间的互换
});
5.解决juery库与其它库之间产生冲突的情况
①解决办法1:把juery的引入放到冲突库的后面
②解决办法2:使用最原始的jQuery来代替$
③解决办法3:用var $$=jQuery;来把用$$来替代$符
④解决办法4:放弃$符的使用,让其它库用,jQuery.noConfig();
6.两种方式对dom进行选取
①使用css进行选取,例如#id
②使用documentGetById,在javascript中使用,对id进行选取
<script>
var element = document.getElementById("targetp");
var tagname = element.tagName; //使用tagName对元素标签名进行选取
alert(tagname);
</script>
7.常规选择器
①简单选择器
jquery的选择器继承了css的语法
1)id选择器
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="box">常规选择器</div>
</body>
</html>
demo.js
$(function () {
//$('#box').css('color', 'blue'); //在juery中的叫法是添加一个行为,这个行为是添加样式
});
2)元素标签选择器
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="box">常规选择器</div>
</body>
</html>
demo.js
$(function () {
//$('div').css('color', 'maroon'); //在juery中的叫法是添加一个行为,这个行为是添加样式
});
3)css选择器
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="pox">div</div>
<div class="pox">div</div>
<div class="pox">div</div>
</body>
</html>
demo.js
$(function () {
//$('.pox').css('color', 'blue');
});
4)通过size()或则length()方法获得选择的元素的个数
例如上述的文件 $(".pox").size() //返回的是3,因为有三个用了class="pox"的div
5)css使用子节点的方法
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="box'>
<p>常规选择器</p>
<p>常规选择器</p>
<p>常规选择器</p>
<div>
<p>常规选择器</p>
<p>常规选择器</p>
<p>常规选择器</p>
</div>
</div>
</body>
</html>
style.css
#box > p { //对子节点进行设置
color:red;
}
#box p{ //对所有box下面的所有p进行设置
color:red;
}
6)jquery使用子节点的方法
demo.js
$(function () {
//$('#box > p').css('color', 'red');
});
7)jquery的逻辑判断的写法
三种方式
demo.js
if ($('#pox').size() > 0) {
$('#pox').css('color', 'red');
}
if ($('#pox').get(0)) {
...
}
if ($('#pox')[0]) {
...
}
8)后代选择器
$(function () {
//$('#box > p').css('color', 'red');
});
8.进阶选择器
①群组选择器
$(function () {
$('div, p, strong').css('color', 'red');
});
②后代选择器
$(function () {
$('ul li a').css('color', 'orange');
});
③通配符选择器
$(function () {
//在全局范围使用*号,会极大的消耗资源,所以不建议在全局使用
//$('ul li *').css('color', 'green');
//alert($('ul li *').size()); //通配选择器一般运用在局部的环境内
});
④限定选择器
例一:
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="box'>div <div>
<p class="box">p</p>
<div>div</div>
<p>p</p>
</body>
</html>
demo.js
$(function () {
//$('div.box').css('color', 'red'); //div下面带有class为.box的进行设定
});
例二:
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="box pox">div</div>
<p class="box">p</p>
<div class="pox">div</div>
<p class="box">p</p>
</body>
</html>
demo.js
$(function () {
$('.box.pox').css('color', 'green');
});
9.高级选择器
①层次选择器
1)后代选择器
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="box">
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<div>
<p>p</p>
<p>p</p>
<p>p</p>
</div>
</div>
</body>
</html>
demo.js
$(function () {
$('#box p').css('color', 'red'); //对box后面所有下一层级的标签都起作用
});
2)使用find来用后代选择器
html参考上面
demo.js
$(function () {
//find()方法
$('#box').find('p').css('color', 'blue');
});
3).子代选择器
html参考上面
demo.js
$(function () {
//find()方法
①//$('#box > p').css('color', 'orange');
②//$('#box').children('p').css('color', 'red');
});
4).兄弟节点选择器
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<div id="box">div</div>
<p>p</p>
<p>p</p>
<p>p</p>
</div>
</body>
</html>
demo.js
$(function () {
①//$('#box + p').css('color', 'blue');
//next()方法
②//$('#box').next('p').css('color', 'maroon'); //相对应的,上一个节点 //$('#box').prev('p').css('color', 'red');
});
5).所有兄弟节点
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<div id="box">div</div>
<p>p</p>
<p>p</p>
<p>p</p>
</div>
</body>
</html>
demo.js
$(function () {
①/nextAll()方法
//$('#box').nextAll('p').css('color', 'maroon');//所有兄弟节点 相对应的上几个兄弟节点 //$('#box').prevAll('p').css('color', 'red');
②//$('#box ~ p').css('color', 'orange');
});
6).上下所有兄弟节点
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<p>p</p>
<p>p</p>
<p>p</p>
<p>p</p>
<div id="box">div</div>
<p>p</p>
<p>p</p>
<p>p</p>
</div>
</body>
</html>
demo.js
$(function () {
//siblings上下同级所有
//$('#box').siblings('p').css('color', 'blue');
});
7)同级上下非指定元素选定,遇到则停止
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<strong>strong</strong>
<strong>strong</strong>
<strong>strong</strong>
<p>p2</p>
<strong>strong</strong>
<strong>strong</strong>
<strong>strong</strong>
<div id="box">div</div>
<strong>strong</strong>
<strong>strong</strong>
<strong>strong</strong>
<p>p1</p>
<strong>strong</strong>
<strong>strong</strong>
<strong>strong</strong>
</body>
</html>
demo.js
$(function () {
//nextUntil()方法
$('#box').nextUntil('p').css('color', 'red'); //同级下非指定元素选定,遇到则停止
//prevUntil()方法
$('#box').prevUntil('p').css('color', 'red'); //同级上非指定元素选定,遇到则停止
});
②属性选择器
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>常规选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<a title="num">num1</a>
<a>num2</a>
<a>num3</a>
<a title="no4">num4</a>
<a bbb="aaa" title="num">num5</a>
</body>
</html>
demo.js
$(function () {
//$('a[title]').css('color', 'red');
//$('a[title=num1]').css('color', 'red');
//$('a[title^=num]').css('color', 'red');
//$('a[title$=num]').css('color', 'red');
//$('a[title|=num]').css('color', 'red');
//$('a[title~=aaa]').css('color', 'red');
//$('a[title*=num]').css('color', 'red');
$('a[bbb][title=num]').css('color', 'red');
});
10.过滤选择器
①基本过滤器
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>过滤选择器</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div style="display:none;">我们的新域名为:ycku.com</div>
<div>我们的旧域名为:yc60.com</div>
<div>1</div>
<div></div>
<ul>
<li>列表1</li>
<li>列表2</li>
<li class="red">列表3</li>
<li>列表4</li>
<li>列表5</li>
<li>列表6</li>
</ul>
<ul>
<li>列表1</li>
<li>列表2</li>
<li>列表3</li>
<li>列表4</li>
<li>列表5</li>
<li>列表6</li>
</ul>
<input type="text" />
<h3>我是标题</h3>
</body>
</html>
demo.js
$(function () {
①//$('li:first').css('background', '#ccc'); 其它写法://$('li').first().css('background', '#ccc');
②//$('li:last').css('background', '#ccc'); 其它写法://$('li').last().css('background', '#ccc');
④//$('ul:first li:last').css('background', '#ccc');
⑤//$('li:not(.red)').css('background', '#ccc'); 其它写法://$('li').not('.red').css('background', '#ccc');
⑥//$('li:even').css('background', '#ccc');
⑦//$('li:odd').css('background', '#ccc');
⑧//$('li:eq(2)').css('background', '#ccc'); 其它写法://$('li').eq(2).css('background', '#ccc');
⑨//$('li:eq(-2)').css('background', '#ccc');
⑩//$('li:gt(3)').css('background', '#ccc');
⑪//$('li:lt(2)').css('background', '#ccc');
⑫//$(' :header').css('background', '#ccc');
⑬//$('input').get(0).focus();
⑭//$(':focus').css('background', 'red');
});
②内容过滤器
demo.js
//$('div:contains("ycku.com")').css('background', '#ccc');
//$('div:empty').css('background', '#ccc').css('height','20px'); //选择空元素
//$('ul:has(.red)').css('background', '#ccc'); //选择子元素含有class是red的元素 其它写法://$('ul').has('.red').css('background', '#ccc');
//$('div:parent').css('background', '#ccc'); //选择含有子元素的div
//alert($('li').parent().size());
//alert($('li').parent().get(0));
//$('li').parent().css('background', '#ccc'); //选择当前元素的父元素
//$('li').parents().css('background', '#ccc'); //选择当前元素的父元素及祖元素
//$('li').parentsUntil('body').css('background', '#ccc'); //选择当前元素遇到div元素停止
//alert($('div:hidden').size()); //元素p隐藏的元素
//$('div:hidden').css('background', '#ccc').show(1000);
//alert($('div:visible').size()); //元素p显示的元素
③子元素过滤器
//$('li:first-child').css('background', '#ccc'); // :first-child $('li:first-child') 获取每个父元素的第一个子元素
//$('li:last-child').css('background', '#ccc'); //获取每个父元素的最后一个子元素
//$('li:only-child').css('background', '#ccc'); //获取只有一个子元素的元素
//$('li:nth-child(even)').css('background', '#ccc'); // 获取每个自定义子元素的元素(索引值从 1 开始计算)
//$('li:nth-child(odd)').css('background', '#ccc');
//$('li:nth-child(5n)').css('background', '#ccc'); //每隔5倍显示
//$('li:nth-child(4n+1)').css('background', '#ccc');
④其它方法
$('.red').is('li'); //true,选择器,检测 class 为是否为 red
$('.red').is($('li')); //true,jQuery 对象集合,同上
$('.red').is($('li').eq(2)); //true,jQuery 对象单个,同上
$('.red').is($('li').get(2)); //true,DOM 对象,同上
$('.red').is(function () { //true,方法,同上
return $(this).attr('title') == '列表 3'; //注意,必须使用$(this)来表示要判断的元素,否则,不管function里面是否返回true或false都和调用的元素无关了
}));
$('li').eq(2).hasClass('red'); //和 is 一样,只不过只能传递 class
$('li').slice(0,2).css('color', 'red'); //前三个变成红色
注意:这个参数有多种传法和注意:这个参数有多种传法和 JavaScript 的 slice 方法是一样的比如:slice(2),从第三个
开始到最后选定;slice(2,4),第三和第四被选定;slice(0,-2)开始到最后选定;slice(2,4),第三和第四被选定;slice(0,-2),从倒数第三个位置,向前选定
所有;所有;slice(2,-2),前两个和末尾两个未选定。
$("div").find("p").end().get(0); //返回 div 的原生 DOM
$('div').contents().size(); //返回子节点(包括文本)数量
$('li').filter('.red').css('background','#ccc'); //选择 li 的 class 为 red 的元素
$('li').filter('.red, :first, :last').css('background','#ccc'); //增加了首尾选择
//特殊要求函数返回
$('li').filter(function () {
return $(this).attr('class') == 'red' && $(this).attr('title') == '列表 3';
}).css('background', '#ccc');}).css('background', '#ccc');
11.使用jQuery来操作基础DOM和CSS操作
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>基础DOM和CSS操作</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="box">
<strong>www.ycku.com</strong>
</div>
<div title="aaa">
<strong>www.ycku.com</strong>
</div>
<div title="bbb">
<strong>www.ycku.com</strong>
</div>
<!--
<input type="text" value="瓢城Web俱乐部" />
<input type="radio" value="男" /> 男
<input type="radio" value="女" /> 女
<input type="checkbox" value="编程" /> 编程
-->
</body>
</html>
1)对标签元素的操作
①html()和 text()方法
$(function () {
//alert($('#box').html()); //获取html的内容 <strong>www.ycku.com</strong>
//alert($('#box').text()); //text获取的是文本,有html会自动被清理 www.ycku.com
//$('#box').html('<em>www.li.cc</em>'); //替换HTML内容,会HTML会自动解析
//$('#box').text('<em>www.li.cc</em>'); //替换文本内容,有HTML会自动转义
});
②使用val()获取表单数据和设置表单数据
$(function () {
//alert($('input').val()); //获取表单里的内容
//$('input').val('北风网'); //设置表单里面的内容
//$('input').val('女'); //设置选中状态
//$('input').val(['男', '女', '编程']);
});
③使用att()方法得到标签属性的相关
$(function () {
//alert($('#box').attr('id')); //得到标签属性的属性值
//$('div').attr('title', '我是域名'); //设置标签的属性值
//对多属性进行设置
//$('div').attr({
// 'title' : '我是域名',
// 'class' : 'red', //class不建议用attr来设置,后面有功能更强大和更丰富的方法代替
// 'data' : '123'
//});
});
④在att()中使用匿名函数
$(function () {
//$('div').attr('title', function () {
// return '我是域名';
//});
//$('div').attr('title', function (index, value) { //value值是先前设置的值
// return '原来的title是:' + value + ',现在的title是:我是' + (index+1) + '号域名';
//});
//$('div').html($('div').html() + '<em>www.li.cc</em>');
//$('div').html(function (index, value) {
// return value + '<em>www.li.cc</em>';
//});
⑤删除标签的属性removeAttr
$(function () {
$('div').removeAttr('title');
//});
2)对元素样式的操作
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>基础DOM和CSS操作</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div title="aaa" class="green">
<strong>www.ycku.com</strong>
</div>
<div title="bbb">
<strong>www.ycku.com</strong>
</div>
</body>
</html>
①使用css()方法
❶css(name)获取单个css样式
$(function () {
$('div').css('color'); //获取css样式});
❷css(name,name)设置单个css样式
$(function () {
//$('div').css('color', 'red'); //设置css样式
});
❸获取多个css样式
//原生态的写法
var box = $('div').css(['color', 'width', 'height']); //获取标签内的多个css样式
for (var i in box) {
alert(i + ':' + box[i]);
}
//jquery的写法
$.each(box, function (attr, value) { //第一个参数是属性名,第二个参数是属性值
alert(attr + ':' + value);
});
❹获取标签元素
$('div').each(function (index, element) {
alert(index + ':' + element);
});
❺设置多个css样式
$('div').css({
'color' : 'blue',
'background-color' : '#eee',
'width' : '200px',
'height' : '30px'
});
❻属性值使用计算后的结果
$('div').css('width', function (index, value) {
//局部操作,很舒服
return parseInt(value) - 500 + 'px';
})
❼给样式分类
除了行内 CSS 设置,我们也可以直接给元素添加 CSS 类,可以添加单个或多个,并且
也可以删除它。也可以删除它。
也可以删除它。
②是用addClass()方法添加css样式
demo.js
$('div').addClass('red'); //添加一个 CSS 类
$('div').addClass('red bg'); //添加多个 CSS 类
$('div').removeClass('bg'); //删除一个 CSS 类
$('div').removeClass('red bg'); //删除多个 CSS 类
style.css
.red {
color:red;
}
.green {
color:green;
}
.bg {
background-color:#ccc;
}
.size {
font-size:20px;
}
③使用toggleClass()来实现样式切换
❶切换两个样式,切换样式和原本样式
$('div').click(function () {
$(this).toggleClass('red size'); //两个样式之间的切换,默认样式和指定样式的切换
});
❷切换自己定义的两个样式
$('div').click(function () {
$(this).toggleClass(function () {
//局部
if ($(this).hasClass('red')) {
$(this).removeClass('red');
return 'green';
} else {
$(this).removeClass('green');
return 'red';
}
});
});
❸使用频率
var count = 0;
$(document).click(function () {
$('div').toggleClass(function (index, className, switchBool) { //第一个是索引,第二是class,第三个是点击的频率
alert(index + ':' + className + ':' + switchBool);
//局部
if ($(this).hasClass('red')) {
$(this).removeClass('red');
return 'green';
} else {
$(this).removeClass('green');
return 'red';
}
}, count++ % 2 == 0);
});
});
3)css的一些方法
①常用方法
$('div').width(); //获取元素的长度,返回的类型为 number
$('div').width(500); //设置元素长度,直接传数值,默认加 px
$('div').width('500pt'); //同上,设置了 pt 单位
$('div').width(function (index, value) { //index 是索引,value 是原本值
return value - 500; //无须调整类型,直接计算
});
$('div').height(); //获取元素的高度,返回的类型为 number
$('div').height(500); //设置元素高度,直接传数值,默认加 px
$('div').height('500pt'); //同上,设置了 pt 单位
$('div').height(function (index, value) { //index 是索引,value 是原本值
return value - 1; //无须调整类型,直接计算
});
②关于边距的方法
alert($('div').width()); //不包含
alert($('div').innerWidth()); //包含内边距 padding
alert($('div').outerWidth()); //包含内边距 padding+边框 border
alert($('div').outerWidth(true)); //包含内边距 padding+边框 border+外边距 margin
③关于偏移值offset
//alert($('div').offset().top); //相对于视口的偏移
//alert($('strong').offset().top);
//alert($('div').position().top); //相对于父元素的偏移
//alert($('strong').offset().top);
//alert($('strong').position().top);
//alert($(window).scrollTop());
$(window).scrollTop(300);
4)对DOM中的Model的操作
①jquery动态创建节点
❶创建和插入节点
$(function () {
var box=$('<div id = "box">节点</div>'); //创建节点
$('body').append(box); //插入节点
});
②插入节点的方法
❶内部插入节点
$(function () {
//插入后面
//$('div').append('<strong>DOM</strong>'); //向指定元素内部后面插入节点 content
//$('div').append(function (index, html) { //使用匿名函数向指定元素内部后面插入节点
// return '<strong>DOM</strong>' + index + html;
//});
//$('strong').appendTo('div'); //移入操作,不需要创建节点
//插入前面
//$('div').prepend('<strong>DOM</strong>');
//$('div').prepend(function (index, html) {
// return '<strong>DOM</strong>' + index + html;
//});
//$('strong').prependTo('div');
});
❷外部插入节点
$(function () {
//$('div').after('<strong>DOM</strong>'); //在同级的后面
//$('div').after(function (index, html) {
// return '<strong>DOM</strong>' + index + html;
//});
//$('div').before('<strong>DOM</strong>'); //在同级的前面
//$('div').before(function (index, html) {
// return '<strong>DOM</strong>' + index + html;
//});
//$('strong').insertAfter('div'); //将已经存在的节点移到另一个节点的后面
//$('strong').insertBefore('div'); //将已经存在的节点移到另一个节点的前面
});
③包裹节点
用节点包裹另外一个节点
$(function () {
//$('div').wrap('<strong class="b"></strong>'); //用strong标签包裹div标签
//$('div').wrap('<strong />');
//$('div').wrap('<strong>123</strong>');
//$('div').wrap('<strong><em></em></strong>');
//$('div').wrap($('strong').get(0));
//$('div').wrap(document.createElement('strong')); //创建一个标签进行包裹
//$('div').wrap(function (index) { //使用匿名函数进行包裹
// return '<strong>' + index + '</strong>'
//});
//$('div').wrap('<strong><em></em></strong>');
//$('div').unwrap(); //解除一层包裹
//$('div').unwrap();
//$('div').wrap('<strong></strong>');
//$('div').wrapAll('<strong></strong>');
//$('div').wrapAll(document.createElement('strong'));
//$('div').wrap('<strong></strong>');
//$('div').wrapInner('<strong></strong>'); //包裹标签内部的内容
//$('div').wrapInner(document.createElement('strong'));
//$('div').wrapInner(function (index) {
// return '<strong>' + index + '</strong>'
//});
});
④对节点的操作,clone,删除之类
$(function () {
$('div').click(function () {
alert('ycku.com');
});
//$('div').clone(true).appendTo('body'); //如果不设置参数true,不会进行事件克隆
//$('div').remove(); //删除节点
//$('div').remove('.box'); //更精确的删除,对包含.box的div进行删除
//alert($('div').remove().get(0)); //返回的是element
//$('div').remove().appendTo('body'); //把删除的节点追加回去(事件无法追加)
//$('div').detach().appendTo('body'); //把删除的节点追加回去(事件可以追加)
//$('div').empty(); //清空节点
//$('div').replaceWith('<span>DOM</span>'); //替换节点
$('<span>DOM</span>').replaceAll('div');
});
⑤对表单节点的选择
1)表单选择器
$(function () {
//alert($('input').val());
//alert($('input[type=password]').val()); //语义清晰一点,
//alert($('input[name=pass]').val());
//alert($('input').size());//获取所有表单字段元素
//alert($(':input[name=city]').size());
//alert($(':text').size());//获取单行文本框元素
//alert($(':password[name=pass]').size()); //获取密码栏元素
//alert($(':radio').size()); //获取单选框元素
//alert($(':radio[name=sex]').eq(1).val());
//alert($(':radio[name=sex]').last().val());
$(':submit).size(); //获取提交按钮元素
$(':reset).size(); //获取重置按钮元素
$(':image).size(); //获取图片按钮元素
$(':file).size(); //获取文件按钮元素
$(':button).size(); //获取普通按钮元素
$(':hidden).size(); //获取隐藏字段元素
});
2)表单过滤器
$(function () {
//alert($('form :hidden').size()); //获取隐藏元素
//alert($('form :enabled').size()); //获取可用元素
//alert($('form :disabled').size());//获取不可用元素
//alert($('form :checked').size()); //获取单选、复选框中被选中的元素
//alert($('form :selected').get(0));//获取下拉列表中被选中的元素
//alert($('form :selected').size());
});
12.基础事件
①绑定事件的方式
$(function () {
/*
$('input').bind('click', function () {//1.匿名函数的方式绑定
alert('弹窗!');
});
$('input').bind('click', fn); //2.通过函数名绑定
function fn() {
alert('处理函数!')
}
$('input').bind('click mouseover', function () { //3.可以同时绑定多个事件
alert('弹窗!');
});
$('input').bind('mouseover mouseout', function () {
$('div').html(function (index, value) {
return value + '1';
});
});
$('input').bind({//展开来写的绑定
mouseover : function () {
alert('移入');
},
mouseout : function () {
alert('移出');
}
});
$('input').bind({
'mouseover' : function () {
alert('移入');
},
'mouseout' : function () {
alert('移出');
}
});
$('input').bind('click mouseover', function () {
alert('弹窗!');
});
$('input').bind('click', fn1);
$('input').bind('click', fn2);
function fn1() {
alert('fn1');
}
function fn2() {
alert('fn2');
}
//$('input').unbind(); //删除全部事件
//$('input').unbind('click'); //只删除click事件
$('input').unbind('click', fn2); //删除click事件绑定了fn2的
});
});
②jquery已经封装好的事件(基本事件)
$(function () {
$('input').click(function () { //单机
alert('单击');
});
$('input').dblclick(function () { //双击
alert('双击');
});
$('input').mousedown(function () {
alert('鼠标左键按下');
});
$('input').mouseup(function () {
alert('鼠标左键按下弹起');
});
$(window).unload(function () {//一般unload卸载页面新版浏览器应该是不支持的,获取要设置一个。
alert('1'); //一般用于清理工作。
});
$(window).resize(function () {
alert('文档改变了');
});
$(window).scroll(function () {
alert('滚动条改变了');
});
$('input').select(function () {
alert('文本选定');
});
$('input').change(function () {
alert('文本改变');
});
*/
$('form').submit(function () {
alert('表单提交!');
});
});
③jquey已经封装好的事件( 基础事件2,需要注意)
1).mouseover() ,.mouseout() 和.mouseenter()和.mouseleave() 的区别
$(function () {
/*
$('div').mouseover(function () {
$(this).css('background', 'red');
}).mouseout(function () {
$(this).css('background', 'green');
});
$('div').mouseenter(function () {
$(this).css('background', 'red');
}).mouseleave(function () {
$(this).css('background', 'green');
});
$('div').mouseover(function() { //over会触发子节点
$('strong').html(function (index, value) {
return value + '1';
});
});
$('div').mouseenter(function() { //enter不会触发子节点
$('strong').html(function (index, value) {
return value + '1';
});
});
$('div').mouseout(function() { //同上
$('strong').html(function (index, value) {
return value + '1';
});
});
$('div').mouseleave(function() { //同上
$('strong').html(function (index, value) {
return value + '1';
});
});
});
2).keydown()、.keyup()返回的是键码,而.keypress()返回的是字符编码
$('input').keydown(function (e) {
alert(e.keyCode); //按下 a 返回 65
});
$('input').keypress(function (e) {
alert(e.charCode); //按下 a 返回 97
})
3).focus() ,.blur()和.focusin() ,.focusout()的区别
$('input').focus(function () { //focus和blur必须是当前元素才能激活
alert('光标激活');
});
$('input').blur(function () {
alert('光标丢失');
});
$('input').focusout(function () {
alert('光标丢失');
});
$('div').focusin(function () { //focusin和focusout可以是子元素激活
alert('光标激活');
});
④jquey的复合事件
1)ready(fn)
当 DOM 加载完毕触发事件
2)hover([fn1,]fn2)
当鼠标移入触发第一个 fn1,移出触发 fn2
注意:.hover()方法是结合了.mouseenter()方法和.mouseleva()方法,并非.mouseover()和.mouseout()方法
$('div').hover(function () {
$(this).css('background', 'red');
}, function () {
$(this).css('background', 'green');
});
3)不断切换执行事件
var flag = 1; //计数器
$('div').click(function () {
if (flag == 1) { //第一次点击
$(this).css('background', 'black');
flag = 2;
} else if (flag == 2) { //第二次点击
$(this).css('background', 'blue');
flag = 3
} else if (flag == 3) { //第三次点击
$(this).css('background', 'red');
flag = 1
}
});
13.jquery的事件对象
①简单演示
$(function () {
$('input').bind('click', function (event) { //参数e是接收回来的值,可以是任何名字(实际上是在封装里面做的),实际上[object,object]
alert(e);
});
});
②event对象的属性
$(function () {
$('input').bind('click', function (e) {
alert(e.type); //对象的类型
});
$('input').bind('click', function (e) {
alert(e.target); //target是获取触发元素的DOM,触发元素,就是你点了哪个就是哪个
});
$('input').bind('click', function (e) {
alert(e.currentTarget); //currentTarget得到的是监听元素的DOM,你绑定的哪个就是那个
});
$('span').bind('mouseover', function (e) {
alert(e.relatedTarget); //获取移入移出目标点离开或进入的那个最相邻的 DOM 元素,例如从div移入span,则返回div
});
$('div').bind('click', function (e) {
alert(this == e.currentTarget); //返回true
});
$('input').bind('click', 123, function (e) {
alert(e.data); //事件获取事件调用时的额外数据,返回123
});
});
③data 获取事件调用时的额外数据(可以是数字、字符串、数组、对象)
$(function () {
$('input').bind('click', 'abc', function (e) {
alert(e.data); //返回字符串
});
$('input').bind('click', [1,2,3,'a','b'], function (e) {
alert(e.data[3]); //[]不代表数组,是表示多个数据
});
$('input').bind('click', {user : 'Lee', age : 100}, function (e) {
alert(e.data.age); //返回对象
});
});
④pageX/pageY 获取相对于页面原点的水平/垂直坐标
screenX/screenY 获取显示器屏幕位置的水平/垂直坐标(非 jQuery 封装)
clientX/clientY 获取相对于页面视口的水平/垂直坐标(非 jQuery 封装)
$(function () {
$(document).bind('click', function (e) {
alert(e.pageX + ',' + e.screenX + ',' + e.clientX);
});
$(document).bind('click', function (e) {
alert(e.pageY + ',' + e.screenY + ',' + e.clientY);
});
});
⑤result,timeStamp,whichaltKey/shiftKey/ctrlKey/metaKey
$('input').bind('click', function (e) {
return 123;
});
$('input').bind('click', function (e) {
alert(e.result);//获取上一个相同事件的返回值,返回123
});
$('input').bind('click', function (e) {
alert(e.timeStamp); //获取事件触发的时间戳
});
$('input').bind('mousedown', function (e) {
alert(e.which); //获取鼠标的左中右键(1,2,3),或获取键盘按键
});
$('input').bind('keyup', function (e) {
alert(e.which); //获取是否按下了 alt、shift、ctrl(这三个非 jQuery 封装)或meta 键(IE 原生 meta 键,jQuery 做了封装)
});
14.冒泡和默认行为
冒泡:当几个dom重叠以后,当点击最小范围的dom时,其它的都会进行触发,例如document有div,div上面有input,当点击input的click事件时,document和div的事件也会触发
默认行文:例如点击链接,它就会连接到另外一个页面,这就是默认行为
$(function () {
//冒泡和阻止冒泡
$('input').click(function (e) {
e.stopPropagation(); //禁止冒泡
e.preventDefault(); //禁止默认行为
e.isDefaultPrevented() //判断是否已经设置了禁止默认行文
e.isPropagationStopped() //判断是否已经设置了禁止冒泡
e.stopImmediatePropagation() //取消事件冒泡,并取消该事件的后续事件处理函数
e.isImmediatePropagationStopped() //判断是否调用了 stopImmediatePropagation()方法
});
});
15.高级事件
①使用trigger模拟点击事件
$(function () {
$('input').click(function () {
alert('我将要使用模拟用户操作来触发!');
});
//模拟用户点击操作
$('input').trigger('click');
$('input').click(function () {
alert('我将要使用模拟用户操作来触发!');
}).trigger('click');
});
②使用trigger得到额外数据
$(function () {
$('input').click(function (e, data1, data2) {
alert(data1 + '|' + data2);
}).trigger('click', ['123', 'abc']);
$('input').click(function (e, data1, data2) {
alert(data1 + '|' + data2);
}).trigger('click', ['123', 'abc']);
//trigger额外数据,只有一条的时候,可以省略中括号,多条不能省略,第二条之后就无法识别了
$('input').click(function (e, data1, data2, data3, data4) {
alert(data1 + '|' + data2 + '|' + data3[1] + '|' + data4.user);
}).trigger('click', ['123', 'abc', ['a', 'b' , 'c'], {user : 'Lee'}]);
$('input').bind('click', {user : 'Lee'} ,function (e, data1, data2, data3, data4) {
alert(data1 + '|' + data2 + '|' + data3[1] + '|' + data4.user + '|' + e.data.user);
}).trigger('click', ['123', 'abc', ['a', 'b' , 'c'], {user : 'Lee'}]);
});
③使用trigger自定义事件
//click,mouseover这些系统事件,自定义事件就是自己起名字的事件
$('input').bind('myEvent', function () {
alert('自定义事件!');
}).trigger('myEvent');
④trigger和triggerHander的区别
triggerHander继承trigger,丰富了trigger
1).triggerHandler()方法并不会触发事件的默认行为,而.trigger()会。
$('form').trigger('submit'); //模拟用户执行提交,并跳转到执行页面
$('form').triggerHandler('submit'); //模拟用户执行提交,并阻止的默认行为
如果我们希望使用.trigger()来模拟用户提交,并且阻止事件的默认行为,则需要这么写:
$('form').submit(function (e) {
e.preventDefault(); //阻止默认行为
}).trigger('submit');
2).triggerHandler()方法只会影响第一个匹配到的元素,而.trigger()会影响所有。
3).triggerHandler()方法会返回当前事件执行的返回值,如果没有返回值,则返回
undefined;而.trigger()则返回当前包含事件触发元素的 jQuery 对象(方便链式连缀调用)。
alert($('input').click(function () {
return 123;
}).triggerHandler('click')); //返回 123,没有 return 返回
4).trigger()在创建事件的时候,会冒泡。但这种冒泡是自定义事件才能体现出来,是
jQuery 扩展于 DOM 的机制,并非 DOM 特性。而.triggerHandler()不会冒泡。
var index = 1;
$('div').bind('myEvent',function(){
alert('自定义事件' + index);
index++;
});
$('.div3').trigger("myEvent");
④命名空间的使用
有时,我们想对事件进行移除。但对于同名同元素绑定的事件移除往往比较麻烦,这个
时候,可以使用事件的命名空间解决。
$('input').bind('click.abc', function () {
alert('abc');
});
$('input').bind('click.xyz', function () {
alert('xyz');
});
$('input').bind('mouseover.abc', function () {
alert('abc');
});
//$('input').unbind('click.abc');
//$('input').unbind('.abc');
$('input').trigger('click.abc');
⑤事件委托
什么是事件委托?用现实中的理解就是:有 100 个学生同时在某天中午收到快递,但这
100 个学生不可能同时站在学校门口等,那么都会委托门卫去收取,然后再逐个交给学生。
而在而在 jQuery 中,我们通过事件冒泡的特性,让子元素绑定的事件冒泡到父元素(或祖先元素)上,然后再进行相关处理即可
//.live的替代方法.delegate
$('#box').delegate('.button', 'click', function () {
$(this).clone().appendTo('#box');
})
$('#box').undelegate('.button', 'click');
//live语义不清晰,由于他没有指定绑定了谁,所以不清晰
//delegate语义清晰,绑定谁,谁就在开头
注意:.live()和.delegate()和.bind()方法一样都是事件绑定,那么区别也很明显,用途上
遵循两个规则:
1.在 DOM 中很多元素绑定相同事件时;
2.在 DOM 中尚不存在即将生成的元素绑定事件时;(例如有些事件是通过clone出来的)
我们推荐使用事件委托的绑定方式,否则推荐使用.bind()的普通绑定。
⑥在新版本中使用on代替bind,使用off代替unbind
注意:不管是.bind()还是.on(),绑定事件后都不是自动移除事件的,需要通过.unbind()和.off()
来手工移除。jQuery 提供了.one()方法,绑定元素执行完毕后自动移除事件,可以方法仅触
发一次的事件。
$(function () {
//普通绑定.bind
//普通解绑.unbind
//事件委托.live .delegate
//解除委托.die .undelegate
//新方法绑定.on
//新方法解绑.off
/*
$('.button').on('click', function () {
alert('替代bind');
});
$('.button').on('click', {user : 'Lee'}, function (e) {
alert('替代bind' + e.data.user);
});
$('.button').on('mouseover mouseout', function (e) {
alert('移入移出');
});
$('.button').on({
mouseover : function () {
alert('移入');
},
mouseout : function () {
alert('移出');
}
});
$('form').on('submit', function () {
return false; //禁止冒泡和默认行为
});
//$('form').on('submit', false); //禁止冒泡和默认行为的简写
$('.button').on('click', function () {
alert('替代bind');
});
$('.button').off('click');
//替代.live .delegate
$('#box').on('click', '.button', function () {
$(this).clone().appendTo('#box');
});
//替代.live .delegate
$('#box').on('click', '.button', function () {
$(this).clone().appendTo('#box');
});
//移出事件委托
$('#box').off('click', '.button');
//仅一次事件触发
$('.button').one('click', function () {
alert('仅一次事件触发!');
});
//仅一次事件触发
$('#box').one('click', '.button', function () {
$(this).clone().appendTo('#box');
});
*/
});
16.动画效果
①显示,隐藏,列队显示,列队隐藏,两种样式来回切换
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>动画效果</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<!--
<div class="test">你</div>
<div class="test">好</div>
<div class="test">吗</div>
<div class="test">?</div>
<input type="button" class="show" value="显示" />
<input type="button" class="hide" value="隐藏" />
<input type="button" class="toggle" value="切换" />
<input type="button" class="up" value="上" />
<input type="button" class="down" value="下" />
<input type="button" class="toggle" value="切换" />
-->
<input type="button" class="in" value="淡入" />
<input type="button" class="out" value="淡出" />
<input type="button" class="toggle" value="切换" />
<input type="button" class="to" value="透明度到" />
<div id="box">
box
</div>
</body>
</html>
style.css
#box {
width:100px;
height:100px;
background:red;
}
.test {
padding:5px;
margin-right:5px;
background:orange;
float:left;
display:none;
}
demo.js
$(function () {
$('.show').click(function () { //显示
$('#box').show();
});
$('.hide').click(function () { //隐藏
$('#box').hide();
});
$('.show').click(function () { //传入显示的执行时间
$('#box').show(1000);
});
$('.hide').click(function () { //传入隐藏的执行时间
$('#box').hide(1000);
});
//可以传递两个参数,一个是速度,第二个是回调函数
$('.show').click(function () {
$('#box').show('fast'); //200 毫秒
});
$('.hide').click(function () {
$('#box').hide('normal'); //400 毫秒
});
//默认是400毫秒
$('.show').click(function () {
$('#box').show('slow'); //600 毫秒
});
$('.show').click(function () { //在执行完显示以后,在执行回调函数,弹出提示框
$('#box').show('slow', function () {
alert('显示完毕!');
});
});
//同步动画,四个区块同时显示出来
$('.show').click(function () {
$('.test').show('slow');
});
//列队动画
$('.show').click(function () { //不停的嵌套,太麻烦
$('.test').eq(0).show('fast', function () {
$('.test').eq(1).show('fast', function () {
$('.test').eq(2).show('fast', function () {
$('.test').eq(3).show('fast');
});
});
});
});
//列队动画,递归自调用
$('.show').click(function () {
$('.test').first().show('fast', function testShow() {
$(this).next().show('fast', testShow);
});
});
//列队进行隐藏
$('.hide').click(function () {
$('.test').last().hide('fast', function testShow() {
$(this).prev().hide('fast', testShow);
});
});
//两种样式来回进行切换
$('.toggle').click(function () {
$('#box').toggle('slow');
});
});
②滑动,卷动,淡入,淡出
1)滑动,卷动
$(function () {
$('.up').click(function () {
$('#box').slideUp('slow');
});
$('.down').click(function () {
$('#box').slideDown('slow');
});
$('.toggle').click(function () {
$('#box').slideToggle('slow');
});
});
2)淡入,淡出
$(function () {
$('.out').click(function () {
$('#box').fadeOut('slow'); //淡出
});
$('.in').click(function () {
$('#box').fadeIn('slow'); //淡入
});
$('.toggle').click(function () {
$('#box').fadeToggle('slow'); //淡入淡出之间互相切换
});
$('.to').click(function () {
$('#box').fadeTo('slow', 0.33); //0-1之间 透明对调制0.33
});
});
③自定义动画
1)最简单示例(同步动画)
$(function () {
$('.button').click(function () {
$('#box').animate({
width : '300px',
height : '200px',
opacity : 0.5,
fontSize : '50px'
});
});
$('.button').click(function () {
$('#box').animate({
width : '300px',
height : '200px',
opacity : 0.5,
fontSize : '50px'
}, 2000, function () {
alert('动画执行完毕!');
}); //第一个参数是样式,第二个参数是执行时间,第三个是回调函数
});
});
注意:一个 CSS 变化就是一个动画效果,上面的例子中,已经有四个 CSS 变化,已经
实现了多重动画同步运动的效果。
2) 移动动画(同步动画)
$(function () {
$('.button').click(function () {
$('#box').animate({
left : '300px', //向左移动到300px的位置
top : '200px' //向上移动到200px的位置
}, 'slow');
});
$('.button').click(function () {
$('#box').animate({
left : '300px'
}, 'slow');
});
$('.button').click(function () { //注意:自定义动画中,每次开始运动都必须是初始位置或初始状态,而有时我们想通过当前位
置或状态下再进行动画。jQuery 提供了自定义动画的累加、累减功能
$('#box').animate({
left : '+=100px'
}, 'slow');
});
});
3)列队动画的实现
❶//回调函数 + 列队动画(任何列队都可以实现,但是太冗肿,不建议)
$('.button').click(function () {
$('#box').animate({
width : '300px'
}, function () {
$('#box').animate({
height : '200px'
}, function () {
$('#box').animate({
opacity : 0.5
}, function () {
$('#box').animate({
fontSize : '50px'
});
});
});
});
});
❷在统一个元素的基础上,使用连缀或顺序排列调用,可以实现列队动画
//在统一个元素的基础上,使用连缀或顺序排列调用,可以实现列队动画
连缀
$('.button').click(function () {
$('#box').animate({width : '300px'})
.animate({height : '200px'})
.animate({opacity : 0.5})
.animate({fontSize : '50px'});
});
//顺序
$('.button').click(function () {
$('#box').animate({width : '300px'});
$('#box').animate({height : '200px'});
$('#box').animate({opacity : 0.5});
$('#box').animate({fontSize : '50px'});
});
❸如果连缀的不是动画,则加入不进去,解决办法
//CSS不是动画方法,会默认排列到和第一个动画方法同步
$('.button').click(function () {
$('#box').slideUp('slow').slideDown('slow', function () {
$(this).css('background', 'orange');
});
});
解决办法:使用next
next
$('.button').click(function () {
$('#box')
.slideUp('slow')
.slideDown('slow')
.queue(
function (next) { //告诉回调函数后面还有
$(this).css('background', 'orange');
next();
}
).hide('slow');
});
❹两个方法length 和clearQueue()
length
.queue()方法还有一个功能,就是可以得到当前动画个列队的长度。当然,这个用法在
普通 Web 开发中用的比较少,我们这里不做详细探讨。
//获取当前列队的长度,fx 是默认列队的参数
function count() {
return $("#box").queue('fx').length;
}
//在某个动画处调用
$('#box').slideDown('slow', function () {alert(count());});
.clearQueue()
jQuery 还提供了一个清理列队的功能方法:.clearQueue()。把它放入一个列队的回调函
数或.queue()方法里,就可以把剩下为执行的列队给移除。
//清理动画列队
$('#box').slideDown('slow', function () {$(this).clearQueue()});
4)动画的常用方法
❶ stop方法
最简单的,点击停止,会立马停止
$(function () {
$('.button').click(function () {
$('#box').animate({
left : '800px'
}, 3000);
});
$('.stop').click(function () {
$('#box').stop();
});
});
针对列队动画的stop
$('.button').click(function () {
$('#box').animate({left : '300px'}, 1000)
.animate({bottom : '300px'}, 1000)
.animate({width : '300px'}, 1000)
.animate({height : '300px'}, 1000)
});
$('.stop').click(function () {
$('#box').stop(true, true);
});
//如果有列队动画,停止的话,那么会停止掉第一个列队动画,然后继续执行后面的列队动画
//第一个参数,如果为true,就是停止并且清除后面的列队动画,动画即完全停止,默认值为false
//第二个参数,如果为true,停止后会跳转到末尾的位置上。,默认值为 false
❷delay方法
$('.button').click(function () {
$('#box').delay(1000) //会延长一秒后再执行后面的列队
.animate({left : '300px'})
.animate({bottom : '300px'}).delay(2000)
.animate({width : '300px'})
.animate({height : '300px'})
});
❸过滤器:animated
$('.ani').click(function () { //过滤出正在运动的动画,使其停止
$(':animated').stop().css('background', 'blue');
});
5)动画的全局属性
❶ jQuery 提供了两种全局设置的属性, 分别为:
$.fx.interval, 设置每秒运行的帧数;$.fx.interval 属性可以调整动画每秒的运行帧数,默认为 13 毫秒。数字越小越流畅,但
可能影响浏览器性能
$.fx.off,关闭页面上所有的动画。
//设置运行帧数为 1000 毫秒
$.fx.interval = 1000; //默认为 13
$('.button').click(function () {
$('#box').toggle(3000);
})
❷运动方式(swing,linear)
$('.button').click(function () {
$('#box').animate({
left : '800px'
}, 3000, 'swing', function () {});
$('#pox').animate({
left : '800px'
}, 3000, 'linear');
});
17.Ajax
①概括:
Ajax 这个概念是由 Jesse James Garrett 在 2005 年发明的。它本身不是单一技术,是一串技术的集合,主要有:
1.JavaScript,通过用户或其他与浏览器相关事件捕获交互行为;
2.XMLHttpRequest 对象,通过这个对象可以在不中断其它浏览器任务的情况下向服务
器发送请求;3.服务器上的文件,以 XML、HTML 或 JSON 格式保存文本数据;
4.其它 JavaScript,解释来自服务器的数据(比如 PHP 从 MySQL 获取的数据)并将其
呈现到页面上。
②jQuery采用了三层封装:
第底层:$.ajax()
第二层:通过最底层封装了,.load()、$.get()和$.post() 三种方法
第三层:$.getScript()和$.getJSON()
③局部 .load()方法
局部:是要由jqury对象的元素作为前缀来使用,适合用于静态文件处理
load()方法有三个参数:url(必须, 请求 html 文件的 url 地址,参数类型为 String)、data(可选,发送的 key/value 数据,参数类型为 Object)、callback(可选,成功或失败的回调函数,参数类型为函数 Function)
//get方式提交
$(function () {
$('input').click(function () {
$('#box').load('test.php?url=ycku'); //加载指定url地址的东西到本地文件中
});
//以post方式提交
$('input').click(function () {
$('#box').load('test.php', {
url : 'ycku'
});
});
//带回调函数的提交
$('input').click(function () {
$('#box').load('test.php', {
url : 'ycku'
}, function (response, status, xhr) { //三个参数,response从服务器端返回的内容,status如果成功返回success, 否则为: error,xhr是一个对象,有如下属性:
responseText就是第一个参数response,
responseXML返回xml等的内容
status就是HTTP状态吗
statusText是状态字符串
![]()
//alert(response);//$('#box').html(response +'123');//if (status == 'success') {alert('成功后的处理');}//alert(xhr.responseText);//alert(xhr.responseXML);//alert(xhr.status);alert(xhr.statusText);
});
});
});
④$.get()方法
方法有四个参数,前面三个参数和.load()一样,多了一个第四参数 type,即服务
器返回的内容格式:包括 xml、html、script、json、jsonp 和 text。第一个参数为必选参数,
后面三个为可选参数
$(function () {
1)//通过直接在url问号紧跟传参
$('input').click(function () {
$.get('test.php?url=ycku', function (response, status, xhr) {
$('#box').html(response);
});
});
2)//通过第二个参数data,字符串形式的键值对传参,然后自动转换为问号紧跟传参
$('input').click(function () {
$.get('test.php', 'url=ycku',function (response, status, xhr) {
$('#box').html(response);
});
});
3)//通过第二个参数data,对象形式的键值对传参,然后自动转换为问号紧跟传参
$('input').click(function () {
$.get('test.php', {
url : 'ycku'
},function (response, status, xhr) {
$('#box').html(response);
});
});
});
⑤$.post()方法
$(function () {
//post提交可以使用字符串形式的键值对传参,自动转换为http消息实体传参
$('input').click(function () {
$.post('test.php', 'url=ycku',function (response, status, xhr) {
$('#box').html(response);
});
});
//post提交可以使用对象键值对
$('input').click(function () {
$.post('test.php',
{
url : 'ycku' //以对象键值对的形式
},
function (response, status, xhr) {
$('#box').html(response);
});
});
//PHP文件返回的数据是纯文本,默认是html或text
$('input').click(function () {
$.post('test.php', {
url : 'ycku'
},function (response, status, xhr) {
$('#box').html(response);
}, 'html'); //PHP文件返回的数据是纯文本,默认是html或text
});
//使用xml格式
$('input').click(function () {
$.post('test.xml',function (response, status, xhr) {
alert($(response).find('root').find('url').text());
});
});
//使用json格式
$('input').click(function () {
$.post('test.json',function (response, status, xhr) {
alert(response[0].url);
});
});
});
注意:GET 方式通过$_GET[]获取,POST 方式通过$_POST[]获取
⑥通过json格式$.getJSON()获取数据
$(function () {
$('input').click(function () {
$.getJSON('test.json',function (response, status, xhr) {
alert(response[0].url);
});
});
});
⑦对js文件的异步加载
$('input').click(function () {
$.getScript('test.js');
});
⑧最底层的方法$.ajax()
1)最简单的ajax
$(function () {$('input').click(function () {$.ajax({type : 'POST',url : 'test.php',data : {url : 'ycku'},success : function (response, status, xhr) {$('#box').html(response);}});});});
2)表单的提交--序列化
键值对形式提交
$(function () {
$('form input[type=button]').click(function () {
$.ajax({
type : 'POST',
url : 'user.php',
data : {
user : $('form input[name=user]').val(),
email : $('form input[name=email]').val(),
},
success : function (response, status, xhr) {
$('#box').html(response);
}
});
});
//表单元素特别多的情况下,写起来非常麻烦,容易出错
//复制提交的JS内容时,data属性需要修改的非常多
//序列化形式提交
$('form input[type=button]').click(function () {
$.ajax({
type : 'POST',
url : 'user.php',
data : $('form').serialize(),
success : function (response, status, xhr) {
$('#box').html(response);
}
});
});
alert($('form').serialize()); //字符串形式的键值对,并且还对URL进行的编码
$('form input[name=sex]').click(function () {
$('#box').html(decodeURIComponent($(this).serialize())); //进行解码
});
});
3)表单的提交--json格式
$('form input[name=sex]').click(function () {
var json = $(this).serializeArray();
$('#box').html(json[0].name + '=' +json[0].value);
});
4)表单提交--$.ajaxSetup(),用来提取初始化重复的属性
$.ajaxSetup({type : 'POST',url : 'user.php',data : $('form').serialize(),});
$('form input[type=button]').click(function () {
$.ajax({
success : function (response, status, xhr) {
$('#box').html(response);
}
});
});
5)$.param()序列环对象
$('form input[type=button]').click(function () {
$.ajax({
type : 'POST',
url : 'user.php',
data : $.param({
user : $('form input[name=user]').val(),
email : $('form input[name=email]').val()
}),
success h: function (response, status, xhr) {
$('#box').html(response);
}
});
});
18.ajax进阶
①加载请求
//请求加载提示的显示和隐藏
$(document).ajaxStart(function () {
$('.loading').show();
}).ajaxStop(function () {
$('.loading').hide();
});
//处理错误1
$(function () {
$('form input[type=button]').click(function () {
$.ajax({
type : 'POST',
url : 'user1.php',
data : $('form').serialize(),
success : function (response, status, xhr) {
$('#box').html(response);
},
//timeout : 500 //如果请求时间太长,可以设置超时
//global : false //如果某个 ajax 不想触发全局事件,可以设置取消
//error : function (xhr, errorText, errorType) { //原生的错误处理方式
//alert('错误!');
//alert(errorText + ':' + errorType);
//alert(xhr.status + ':' + xhr.statusText);
//}
});
});
//错误处理2,局部
$.post('user1.php').error(function (xhr, errorText, errorType) {
//alert('错误');
alert(errorText + ':' + errorType);
alert(xhr.status + ':' + xhr.statusText);
});
//错误处理3,全局
$(document).ajaxError(function (event, xhr, settings, errorType) {
//alert(event.type);
//alert(event.target);
//for (var i in event) {
// document.write(i + '<br />');
//}
//alert(settings);
//for (var i in settings) {
// document.write(i + '<br />');
//}
//alert(settings.url);
//alert(settings.type);
alert(info);
});
②对请求的各个阶段的处理,类似swing的监听
$('form input[type=button]').click(function () {
//1.post,局部
$.post('user1.php', $('form').serialize()).success(function () {
alert('请求成功后!');
}).complete(function () {
alert('请求完成后!');
}).error(function () {
alert('请求失败后!');
});
//2.ajax,局部
$.ajax({
type : 'POST',
url : 'user.php',
data : $('form').serialize(),
success : function (response, status, xhr) {
alert('请求成功后');
},
complete : function () {
alert('请求完成后,不管是否失败成功');
},
beforeSend : function () {
alert('发送请求之前执行');
},
error : function () {
alert('请求失败后');
}
});
});
$(document).ajaxSend(function () {
alert('发送请求之前执行');
}).ajaxComplete(function () {
alert('请求完成后,不管是否失败成功');
}).ajaxSuccess(function () {
alert('请求成功后');
}).ajaxError(function () {
alert('请求失败后');
});
③ json访问本地和远程
$(function () {
$('form input[type=button]').click(function () {
//本地获取jsonp.php文件,成功
$.ajax({
type : 'POST',
url : 'jsonp.php',
dataType : 'json',
success : function (response, status, xhr) {
//alert(response);
alert(response.a);
}
});
//$.ajax()获取远程数据
$.ajax({
type : 'POST',
url : 'http://www.li.cc/jsonp2.php',
dataType : 'jsonp',
success : function (response, status, xhr) {
//alert(response);
console.log(response);
alert(response.a);
}
});
});
④jqXHR 对象
1)概述:我们使用了局部方法:.success()、.complete()和.error()。这三个局部方法并不
是 XMLHttpRequest 对象调用的, 而是$.ajax()之类的全局方法返回的对象调用的。 这个对象,
就是 jqXHR 对象,它是原生对象 XHR 的一个超集
//获取 jqXHR 对象,查看属性和方法
var jqXHR = $.ajax({
type : 'POST',
url : 'test.php',
data : $('form').serialize()
});
for (var i in jqXHR) {
document.write(i + '<br />');
}
注意:如果使用 jqXHR 对象的话,那么建议用.done()、.always()和.fail()代
替.success()、.complete()和.error()。以为在未来版本中,很可能将这三种方法废弃取消
//成功后回调函数
jqXHR.done(function (response) {
$('#box').html(response);
});
//同时执行多个成功后的回调函数
jqXHR.done().done();
//多个操作指定回调函数
var jqXHR = $.ajax('test.php');
var jqXHR2 = $.ajax('test2.php');
$.when(jqXHR, jqXHR2).done(function (r1,r2) {
alert(r1[0]);
alert(r2[0]);
});
19.工具函数
①字符串
$(function () {
var str = ' jQuery ';
alert(str);
alert($.trim(str)); //去空格
});
②数组和对象操作
$(function () {
var arr = ['张三', '李四', '王五', '马六'];
$.each(arr, function (index, value) { //数组的遍历
$('#box').html($('#box').html() + (index+1) + '.' + value + '<br />');
});
$.each($.ajax(), function (name, fn) { //对对象的遍历
$('#box').html($('#box').html() + name + '<br /><br />');
});
var arr = [4,2,6,9,11,25,38,59];
var arrGrep = $.grep(arr, function (element, index) { //对数组进行检索
return index < 5 && element < 6; //这里按道理是布尔值,但整体返回一个数组
});
alert(arrGrep);
var arr = [4,2,6,9,11,25,38,59];
var arrMap = $.map(arr, function (element, index) { //对数组检索,检索是否存在
//return index < 5 && element < 6; //这里就是按布尔值返回的
if (index < 5 && element < 6) {
return element + 1;
}
});
alert(arrMap);
var arr = [4,2,6,9,11,25,38,59];
alert($.inArray(11, arr)); //查找元素下标
var arr = [4,2,6,9,11,25,38,59];
var arr2 = [200,300];
alert($.merge(arr, arr2));//合并两个数组
//$.unique()删除重复的 DOM 元素
<div></div>
<div></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div></div>
var divs = $('div').get();
divs = divs.concat($('.box').get());
alert($(divs).size());
$.unique(divs);
alert($(divs).size())
//dom元素的数量
alert($('li').toArray().length);
alert($($('li').toArray()).size());
});
③测试操作
//判断是否为数组对象
var arr = [1,2,3];
alert($.isArray(arr));
//判断是否为函数
var fn = function () {};
alert($.isFunction(fn));
//判断是否为空对象
var obj = {}
alert($.isEmptyObject(obj));
//判断是否由{}或 new Object()创造出的对象
var obj = window;
alert($.isPlainObject(obj));
注意:如果使用 new Object('name');传递参数后,返回类型已不是 Object,而是字符串,
所以就不是纯粹的原始对象了。
所以就不是纯粹的原始对象了。
//判断第一个 DOM 节点是否含有第二个 DOM 节点
alert($.contains($('#box').get(0), $('#pox').get(0)));
//$.type()检测数据类型
alert($.type(window));
//$.isNumeric 检测数据是否为数值
alert($.isNumeric(5.25));
//$.isWindow 检测数据对象是否为 window 对象
alert($.isWindow(window));
④URL 操作
//$.param()将对象键值对转换为 URL 字符串键值对
var obj = {
name : 'Lee',
age : 100
};
alert($.param(obj)); //name='Lee'&age=100
⑤$.proxy()
//$.proxy()调整 this 指向
var obj = {
name : 'Lee',
test : function () {
alert(this.name);
}
};
$('#box').click(obj.test); //指向的 this 为#box 元素
$('#box').click($.proxy(obj, 'test')); //指向的 this 为方法属于对象 box
20.插件
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>插件</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript" src="jquery.validate.messages_zh.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script type="text/javascript" src="jquery-migrate-1.2.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="stylesheet" href="jquery.autocomplete.css" type="text/css" />
</head>
<body>
<form action="123.html">
<p>用 户 名:<input type="text" class="required" minlength="2" name="user" /> (*)</p>
<p>电子邮件:<input type="text" class="required email" name="email" /> (*)</p>
<p>网 址:<input type="text" class="url" name="url" /></p>
<p><input type="submit" value="提交" /></p>
</form>
</body>
</html>
$(function () {
//第一步,引入jquery文件
//第二步,引入validate.js
//第三步,加载validate
$('form').validate();
//第四步,不得为空,给表单字段class="required"
var user = ['about', 'famliy', 'but', 'black'];
$('form input[name=user]').autocomplete(user, {
minChars : 0
});
});
21.自定义插件的约定
经过日积月累的插件开发,开发者逐步约定了一些基本要点,以解决各种因为插件导致
的冲突、错误等问题,包括如下:
1.插件名推荐使用 jquery.[插件名].js,以免和其他 js 文件或者其他库相冲突;
2.局部对象附加 jquery.fn 对象上,全局函数附加在 jquery 上;
3.插件内部,this 指向是当前的局部对象;
4.可以通过 this.each 来遍历所有元素;
5.所有的方法或插件,必须用分号结尾,避免出现问题;
6.插件应该返回的是 jQuery 对象,以保证可链式连缀;
7.避免插件内部使用$,如果要使用,请传递 jQuery 进去。
22.制作header
//JS 引入和 CSS 引入
<script type="text/javascript" src="js/jquery.js"></script> //http://jqueryui.com/ 下载的包中的js文件夹下的jquery-1.10.1.js
<script type="text/javascript" src="js/jquery.ui.js"></script> //http://jqueryui.com/ 下载包中的js文件夹下面的jquery.ui-1.10.3.custom.js
<script type="text/javascript" src="js/jquery.validate.js"></script> //http://bassistance.de/jquery-plugins/jquery-plugin-validation 下载表单验证插件jquery.validate.js
<script type="text/javascript" src="js/jquery.form.js"></script> //http://malsup.com/jquery/form/ 下载表单插件
<script type="text/javascript" src="js/index.js"></script> //自己定义的js
<link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" /> //网站logo图标
<link rel="stylesheet" href="css/smoothness/jquery.ui.css" type="text/css" /> //http://jqueryui.com/ 下载包中的css主题文件夹下的jquey-ui-1.10.3.custom.css
<link rel="stylesheet" href="css/style.css" type="text/css" /> //自己定义的css
23.ajax表单提交
下载form插件:http://malsup.com/jquery/form/
①ajaxForm()
form表单
<form id="reg" method="post" action="add.php">
<p class="myerror"></p>
<p>帐号:<input type="text" name="user" id="user" /></p>
<p>密码:<input type="text" name="pass" id="pass" /></p>
<p><input type="submit" value="提交" /></p>
</form>
//ajaxForm 提交方式
$('#reg').ajaxForm(function () {
alert('提交成功!'); //function相当于success
});
注意:使用 ajaxForm()方法,会直接实现 ajax 提交。自动阻止了默认行为,而它提交的
默认页面是 form 控件的 action 属性的值。提交的方式是 method 属性的值。
②ajaxSubmit()
注意:ajaxForm()方法,是针对 form 直接提交的,所以阻止了默认行为。而 ajaxSubmit()
方法,由于是针对 submit()方法的,所以需要手动阻止默认行为。而使用了 validate.js 验证
插件,那么 ajaxSubmit()比较适合我们。
③工具方法
form.js 除了提供两个核心方法之外,还提供了一些常用的工具方法。这些方法主要是
在提交前或后对数据或表单进行处理的。
//表单序列化
alert($('#reg').formSerialize());
//序列化某一个字段
alert($('#reg #user').fieldSerialize());
//得到某个字段的 value 值
alert($('#reg #user').fieldValue());
//重置表单
$('#reg').resetForm()
//清空某个字段
$('#reg #user').clearFields();
24.dialog
①dialog 外观选项
$('#reg').dialog({
title : '知问注册',
buttons : {
'提交' : function () { //dialog 外观选项
alert('正在Ajax提交中...');
},
'取消' : function () {
$(this).dialog('close');
}
},
//position : 'left top', //dialog位置选项
//width : 500,
//height : 400,
//minWidth : 300,
//minHeight : 300
//maxWidth : 700,
//show : 'puff',
//hide : 'puff', //打开隐藏的视觉效果
//autoOpen : false, //是否在加载的时候就自动打开
//draggable : false, //可否被拖动
//resizable : false, //大小能否改变
modal : true, //对话框外是否可以操作
closeText : '关闭' //
});
②dialog()方法的属性
$(function () {
$('#reg').dialog({
focus : function (e, ui) { //获得焦点指定回调
alert('注册!');
}
});
$('#login').dialog({
focus : function (e, ui) {
alert('登录!');
}
});
$('#reg').dialog({
/*
create : function (e, ui) { //在对话框创建时回调
alert('创建!');
},
autoOpen : false,
open : function () { //在对话框打开是回调
alert('打开!');
},
autoOpen : false,
close : function () { //在对话框关闭时回调
alert('关闭!');
},
//这个事件可以做一些关闭确认的工作
beforeClose : function () { //在对话框即将关闭时回调
alert('将要关闭时!');
return false;
},
drag : function () { //在对话框被拖动时回调
alert('每次移动都执行');
},
drag : function (e,ui) { //在对话框被拖动是打出包含的属性
alert('top:' + ui.position.top + '\n'
+ 'left:' + ui.position.left);
},
dragStart : function (e,ui) { //在对话框干开始时
alert('top:' + ui.position.top + '\n'
+ 'left:' + ui.position.left);
},
dragStop : function (e,ui) { //在对话框停止时
alert('top:' + ui.position.top + '\n'
+ 'left:' + ui.position.left);
},
resize : function () { //在度画框改变大小时
alert('每次调整大小都执行');
},
resize : function (e, ui) { //在对话框改变大小时得到一些属性
alert('width:' + ui.size.width + '\n'
+ 'height:' + ui.size.height);
},
resizeStop : function (e, ui) { //在对话框大小停止改变时
alert('width:' + ui.size.width + '\n'
+ 'height:' + ui.size.height);
},
*/
autoOpen : true,
});
$('#reg_a').click(function () { //点击打开对话框
$('#reg').dialog('open');
});
$('#reg').click(function () { //点击关闭对话框
//$('#reg').dialog('close');
//$('#reg').dialog('destroy');
});
//alert($('#reg').dialog('isOpen')); //判断对话框是否打开
//$('#reg').dialog('open');
//$('#reg').dialog('widget').css('font-size', '50px'); //得到整个对话框
//alert($('#reg').dialog('option', 'title')); //得到对话框的属性值
//alert($('#reg').dialog('option', 'autoOpen'));
//$('#reg').dialog('option', 'title', '111'); //设置对话框的属性值
$('#reg').on('dialogclose', function () {
alert('关闭');
});
});
25.按钮
①按钮的属性
$('#search_button').button({
//disabled : true,
//label : '搜索',
icons : {
primary : 'ui-icon-search',
//secondary : 'ui-icon-triangle-1-s'
}
//text : false
});
②按钮的方法
$('#search_button').button({
//disabled : true,
//label : '搜索',
icons : {
primary : 'ui-icon-search',
//secondary : 'ui-icon-triangle-1-s'
}
//text : false
});
$('#search_button').button('disable'); //设置按钮状态
$('#search_button').button('enable');
$('#search_button').click(function () {
alert('');
});
*/
$('#reg').dialog({
buttons : {
'提交' : function () {
}
}
});
//$('#reg').parent().find('button').eq(1).button('disable'); //找到dialog中的按钮
//$('#reg').dialog('widget').find('button').eq(1).button('disable');
//$('#reg input[type=radio]').button(); //把单选按钮变成button
//$('#reg').buttonset();
//$('#reg input[type=checkbox]').button(); //把复选框变成按钮
$('#reg').buttonset();
26.自动补全
var host = ['aa', 'aaaa', 'aaaaaa', 'bb'];
$('#email').autocomplete({
source : host,
//disabled : true,
//minLength : 2,
minLength : 0
//delay : 0,
//autoFocus : true, //默认聚焦在第一个选项上
//position : {
// my : 'left center',
// at : 'right center'
//}
//focus : function (e, ui) {
//alert('获取焦点!');
//alert(ui.item.label);
//ui.item.value = 123;
//},
//select : function () {
// alert('选定一个项目!');
//}
//change : function () {
// alert('改变!');
//}
//search : function () {
// alert('搜索完毕!');
//}
//response : function (e, ui) {
// alert('搜索完毕!');
// alert(ui.content[1].label)
//}
});
27. 校验
$(function () {
//所有默认行为都可以在这里设置
//$.validator.setDefaults({
// debug : true, //开启debug,禁止默认行为
//});
$('#reg').validate({
//debug : true,
submitHandler : function (form) {
//alert(form);
//当验证成功后执行,而且阻止了默认提交
//一般用于ajax提交使用
//$('.myerror').hide();
alert('验证成功,准备提交!');
},
//ignore : '#pass',
//groups : {
// myerror : 'user pass',
//},
/*
focusInvalid : false,
errorPlacement : function (error, element) {//显示群组的错误提示
//alert(element[0]);
//alert(error);
$.each(error, function (index, value) {
//alert(index + ' ' + $(value).html());
$('.myerror').html($('.myerror').html() + $(value).html());
});
},
groups : { //群组错误提示,分开
error_user : 'user',
error_pass : 'pass',
},
errorPlacement : function (error, element) {//将群组的错误指定存放位置
error.appendTo('.myerror');
},
errorClass : 'abc',//设置错误提示的 class 名
errorElement : 'p', //设置错误提示的标签
errorLabelContainer : 'ol.myerror', //统一包裹错误提示
wrapper : 'li',
*/
//success : 'abc', //设置成功后加载的 class
//success : function (label) { //使用方法加载 class 并添加文本
// label.addClass('abc').text('ok');
//},
/*
highlight : function (element, errorClass) { //高亮显示有错误的元素,变色式
$(element).css('border', '1px solid red');
},
//高亮显示有错误的元素,变色式
highlight: function(element, errorClass) {
$(element).css('border', '1px solid red');
},
unhighlight : function (element, errorClass) { //成功的元素移出错误高亮
$(element).css('border', '0px solid red');
},
*/
/*
invalidHandler : function (event, validator) { //表单提交时获取信息
var error = validator.numberOfInvalids();
if (error) {
$('.myerror').html('您有' + error + '条错误信息!');
}
},
*/
showErrors : function (errorMap, errorList) { //获取错误提示句柄,不用提交及时获取值
//$.each(errorMap, function (index,value) {
//alert(index + ' ' + value);
//});
//alert(errorMap.user);
//alert(errorList[0].element); //得到错误信息
//alert(errorList[0].message); //当前错误的表单元
var error = this.numberOfInvalids();
if (error) {
$('.myerror').html('您有' + error + '条错误信息!');
} else {
$('.myerror').hide();
}
this.defaultShowErrors(); //执行默认错误
},
rules : { //校验规则
user : {
required : true,
minlength : 2,
//rangelength : [5,10]
},
pass : {
required : true,
minlength : 6,
}
},
messages : { //通不过校验时提示的信息
user : {
required : '帐号不得为空!',
minlength : jQuery.format('帐号不得小于{0}位!'),
//rangelength : jQuery.format('帐号必须在{0}-{1}之间!'),
},
pass : {
required : '密码不得为空!',
minlength : jQuery.format('密码不得小于{0}位!'),
},
}
});
});
28.ajax验证
使用 remote:url,可以对表单进行 ajax 验证,默认会提交当前验证的值到远程地址。如
果需要提交其他的值,可以使用 data 选项。
①//使用 ajax 验证,传一个值
rules : {
user : {
required : true,
minlength : 2,
remote : 'user.php',
},
},
//user.php 内容
<?php
if ($_GET['user'] == 'bnbbs') {
echo 'false';
} else {
echo 'true';
}
?>
注意:远程地址只能输出'true'或'false',不能输出其他值
②//同时传递多个值到远程端
rules : {
user : {
required : true,
minlength : 2,
//remote : 'user.php',
},
pass : {
required : true,
minlength : 6,
remote : {
url : 'user.php',
type : 'POST',
dataType : 'json',
data : {
user : function () {
return $('#user').val();
},
},
},
}
},
messages : {
user : {
//required : '帐号不得为空!',
//minlength : jQuery.format('帐号不得小于{0}位!'),
//remote : '帐号被占用!',
},
pass : {
required : '密码不得为空!',
minlength : jQuery.format('密码不得小于{0}位!'),
remote : '帐号或密码不正确!',
},
}
//user.php 内容
<?php
if ($_POST['user'] != 'bnbbs' || $_POST['pass'] != '123456') {
echo 'false';
} else {
echo 'true';
}
?>
③为单独的属性设置校验
$('#user').rules('add', {
required : true,
minlength : 2,
messages : {
required : '帐号不得为空!',
minlength : jQuery.format('帐号不得小于{0}位!'),
},
});
//$('#user').rules('remove');
//$('#user').rules('remove', 'minlength min max'); //移除某个校验
④//自定义校验
$('#code').rules('add', {
required : true,
code : true,
messages : {
required : '邮编不得为空!',
},
});
$.validator.addMethod('code', function (value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, '请输入正确的邮政编码!');
29.cookie插件
①插件下载地址
http://plugins.jquery.com/cookie/
②cookie的查看:浏览器工具-->选项-->隐私-->移除个人cookie
③生成cookie:
$.cookie('user', 'bnbbs'); //生成一个 cookie:
/*
$.cookie('user', 'bnbbs', {
expires : 7, //设置cookie保存时间,7天
path : '/', //设置cookie在客户端的保存路径
});
*/
//$.cookie('aaa', 'bbb', {
// //domain : 'www.ycku.com', //设置域名
// secure : true, //默认为 false,需要使用安全协议 https
//});
//alert($.cookie('user'));
//alert($.cookie('aaa'));
//$.cookie('ccc', '李炎恢'); //默认进行编码
//alert($.cookie('ccc'));
//$.cookie.raw = true, //关闭编码/解码,默认为 false
//$.cookie('ddd', '李炎恢');
//alert($.cookie('ddd'));
//alert($.cookie().ccc);
//$.removeCookie('user', { //删除cookie
// path : '/',
//});
30.选项卡UI
①写法
在html中的写法固定
<div id="tabs">
<ul>
<li><a href="#tab1">tab1</a></li>
<li><a href="#tab2">tab2</a></li>
<li><a href="#tab3">tab3</a></li>
</ul>
<div id="tab1">tab1-content</div>
<div id="tab2">tab2-content</div>
<div id="tab3">tab3-content</div>
</div>
在js中加上
$('#tabs').tabs({
//collapsible : true, //折叠控制
//disabled : [0,1], //部分禁用选项卡
//disabled : true, //禁用全部
//event : 'mouseover', //鼠标悬浮的时候可以选择选项卡
//active : 1, //默认选中哪个选项卡,从0开始
//active : false, //设成false,默认不折叠
//heightStyle : 'content', //根据内容的高度而调高度的
//heightStyle : 'auto', //根据高的那个选项卡来规定其它选项卡的高度
//heightStyle : 'fill', //全部填充
//show : true, //淡入
//hide : true, //淡出
//可选特效
②方法事件
//方法事件
/*
create : function (event, ui) {
//alert('创建tab时触发!');
alert($(ui.tab.get()).html());
alert($(ui.panel.get()).html());
},
activate : function (event, ui) {
//alert('切换到另一个活动卡后触发!');
//alert($(ui.oldTab.get()).html());
//alert($(ui.newTab.get()).html());
alert($(ui.oldPanel.get()).html());
alert($(ui.newPanel.get()).html());
},
*/
beforeActivate : function (event, ui) {
//alert('切换到另一个活动卡之前触发!');
alert($(ui.oldTab.get()).html());
alert($(ui.newTab.get()).html());
alert($(ui.oldPanel.get()).html());
alert($(ui.newPanel.get()).html());
},
load : function (event, ui) {
//alert('ajax远程加载文档后触发!');
alert($(ui.tab.get()).html()); //得到tab
alert($(ui.panel.get()).html()); //得到panel
},
beforeLoad : function (event, ui) {
//alert('ajax远程加载文档前触发!');
//alert($(ui.tab.get()).html());
//alert($(ui.panel.get()).html());
//ui.jqXHR.success(function (responseText) {
// alert(responseText);
//});
//ui.ajaxSettings.url = 'tab3.html'; //设置一些默认值
},
*/
③对选项卡的设置
//$('#tabs').tabs('disable'); //禁用选项卡
//$('#tabs').tabs('disable', 0); //启用选项卡
//$('#tabs').tabs('enable', 0); //获取选项卡的 jQuery 对象
tabs('refresh') //jQuery 对象 更新选项卡,比如高度。
tabs('option', param) //一般值 获取 options 属性的值
tabs('option', param, value) //jQuery 对象 设置 options 属性的值
④采用load的异步加载
$('#button').click(function () {
$('#tabs').tabs('load', 0); //加载第一个选项卡的内容,用ajax方式
});
⑤on()
$('#tabs').on('tabsload', function (event, ui) {
alert('ajax远程加载文档后触发!'); //
});
});
31.折叠菜单(略……)
和选项卡类似,参见文档
32.$.type来实现类型判断
也许大家都已经习惯了使用JavaScript的本地方法:typeof 来判断类型,但是在jQuery中提供了一个更好的方法帮助你判断类型,那就是$.type。
那么究竟有什么区别呢? 我们先看看这个gbdebug:
http://www.gbtags.com/gb/debug/3361dbff-41c0-465d-81e3-1ef6cbb275e1.htm
运行以上代码,能看到如下输出结果:
大家看出来什么区别了吗? 使用$.type能够返回更准确的对象类型,而typeof则返回object,所以如果你使用jQuery来编码的时候,使用$.type 将更加方便。