jQuery学习笔记1
开始之前:http://docs.jquery.com/ 是jQuery文档的网站, https://jsfiddle.net/是js的在线验证工具。
1.首先复习一下html, css, js三个文件的协同作用
- html负责内容elements和骨架tags,div
- css负责格式样式大小、颜色等
- js负责动作效果,操作html
JQuery是一个面向javascript的工具库,基于DOM-Document Object Model文档对象模型,通过使用jQuery可以方便实现效果。
1.1-html包含css与JavaScript的基本骨架代码
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title></title>
5. <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
6. <script type="text/javascript" src="script.js"></script>
7. </head>
8. <body>
9. <div id="red" ></div>
10. </body>
11. </html>
2.好,让我们开始接触jQuery
Getting Started
Next, we’ll need to start up our jQuery magic using the $(document).ready(); syntax you’ve seen. It works like this:
1. $() says, "hey, jQuery things are about to happen!"是把()内的东东转化成jQuery的object,从而有后面的.ready这个method
2. Putting document between the parentheses tells us that we're about to work our magic on the HTML document itself.
3. .ready(); is a function, or basic action, in jQuery. It says "hey, I'm going to do stuff as soon as the HTML document is ready!"
4. Whatever goes in .ready()'s parentheses is the jQuery event that occurs as soon as the HTML document is ready.
So,
$(document).ready(something);
//就是对于document来说,当你ready的时候,就执行something
3.好,我们来玩玩嵌套的method
1. $(document).ready(
2. function(){
3. $('div').mouseenter(
4. function(){
5. $('div').fadeTo('fast',1);
6. }
7. );
8. $('div').mouseleave(
9. function(){
10. $('div').fadeTo('fast',0.5)
11. }
12. );
13. }
14. );
这个就是先(document)ready , 然后(div)mouseenter,最后(div)fadeTo.
实际上这个排版不是很通用,通用的排版应该是:
1. $(document).ready(function(){
2. $('div').mouseenter(function(){
3. $('div').fadeTo('fast',1);
4. });
5. $('div').mouseleave(function(){
6. $('div').fadeTo('fast',0.5)
7. });
8. });
4.关于CSS中的selector
在有列表情况下,如果想通过js对列表中的某一项进行操作,需要用到selector来指定是修改哪一个:比如:
1. <ol>
2. <li>Start with the function keyword</li>
3. <li>Inputs go between ()</li>
4. <li>Actions go between {}</li>
5. <li id="no4" class="hide">jQuery is for chumps!</li>
6. </ol>
这个html列表,我们jQuery可以用CSS的这4种方法来指明:
- id
- class
- nth-child(n)
- last-child
1. // Write your jQuery code on line 3!
2. $(document).ready(function() {
3. var $target = $('li#no4') //use an id or class
4. //var $target = $('li.hide') //use a class
5. //var $target = $('li:nth-child(4)') //use "nth-child(n)"
6. //var $target = $('li:last-child') //use "last-child"
7. $target.fadeOut('fast');
8. });
另外,需要同时定位2个标签、class、id时,还可使用如下方式:
$('p, li').fadeOut('slow');
$('.red, .pink').fadeOut('slow');
$('#green, #blue').fadeOut('slow');
5.使用‘this’,在jQuery中
this 这个key word在jQuery中可以理解为:当你涉及到诸如mouseenter, click这样的事件类function时,使用this可以在你后续处理动作时指定就是你上次事件指向的那个object,比如有多个div,当你点击了第一个div时,你要让它消失,就在click后用this来让它消失:
1. $(document).ready(function() {
2. $('div').click(function() {
3. $(this).fadeOut('slow'); //对上次事件的对象进行fadeOut操作
4. });
5. });
原html部分代码如下:
1. <body>
2. <div></div>
3. <div></div>
4. <div></div>
5. <div></div>
6. </body>
6.关于Toggling Our Panel的实例
本实例要实现点击下拉一个div出来的效果,先用display:none在CSS中将div隐藏,再在js中调用jQuery的slideToggle()函数:
部分html代码如下:
1. <body>
2. <div class="panel">
3. <br />
4. <br />
5. <p>Now you see me!</p>
6. </div>
7. <p class="slide"><div class="pull-me">Slide Up/Down</div></p>
8. </body>
全部CSS代码如下:
1. body {
2. margin:0 auto;
3. padding:0;
4. width:200px;
5. text-align:center;
6. }
7. .pull-me{
8. -webkit-box-shadow: 0 0 8px #FFD700;
9. -moz-box-shadow: 0 0 8px #FFD700;
10. box-shadow: 0 0 8px #FFD700;
11. cursor:pointer;
12. }
13. .panel {
14. background: #ffffbd;
15. background-size:90% 90%;
16. height:140px;
17. display:none; /*there we go*/
18. font-family:garamond,times-new-roman,serif;
19. }
20. .panel p{
21. text-align:center;
22. }
23. .slide {
24. margin:0;
25. padding:0;
26. border-top:solid 2px #cc0000;
27. }
28. .pull-me {
29. display:block;
30. position:relative;
31. right:-25px;
32. width:150px;
33. height:20px;
34. font-family:arial,sans-serif;
35. font-size:14px;
36. color:#ffffff;
37. background:#cc0000;
38. text-decoration:none;
39. -moz-border-bottom-left-radius:5px;
40. -moz-border-bottom-right-radius:5px;
41. border-bottom-left-radius:5px;
42. border-bottom-right-radius:5px;
43. }
44. .pull-me p {
45. text-align:center;
46. }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
全部js代码如下:
1. $(document).ready(function(){
2. $('.pull-me').click(
3. function(){
4. $('.panel').slideToggle('slow');
5. });
6. });
到这里就掌握了基本的jQuery用法,完成了对于jQuery函数和selector的学习,接下来要学习jQuery的“modify HTMLElements”
Any time you have questions about what jQuery can do or how it works, you can always check out the jQuery documentation, which covers every aspect of the library. 所以:http://docs.jquery.com/ 是jQuery文档的网站。
7.开始修改HTML中的元素
Dynamically adding elements to our HTML page is a powerful tool—it lets us modify not only the formatting, but the actualstructure of our websites in response to a user’s actions. 不仅可以改格式,还可以改页面结构。
不单是这样:
$p = $('p');
还可以是这样:
$p = $("<p>I'm a new paragraph!</p>"); //把一个String放到$p变量里去
7.1 -Inserting Elements
We can insert our newly created elements using a few jQuery actions.
`.append()` inserts the specified element as the last child of the target element. `.prepend()` inserts the specified element as the *first* child of the target element. If we have a div of class `.info`,:
- $(".info").append("
Stuff!
");//inserts element as the last child of the target - $(".info").prepend("
Stuff!
"); //inserts as the first
$('<p>Stuff!</p>').appendTo('.info'); //appendTo('.target tag'); = append
7.2 - before and after
用.before 和 .after来定位where we insert an element. 语法如下:
$('target').after('<tag>To add</tag>');
target 就是定位加入<tag>To add</tag>的位置,在target后面加入。
html示例代码:
1. <body>
2. <div class="container">
3. <h2>Greetings</h2>
4. <div id="one">Div #1</div>
5. <div id="two">Div #2</div>
6. </div>
7. </body>
js代码:
1. $(document).ready(function(){
2. $("div#one").after("<p>I'm joined here.</p>");
3. });
7.3 - move around
js代码:
$(document).ready(function(){
$("div#one").after("<p>I'm joined here.</p>"); //insert the <p> tag
var $paragraph = $("p"); //move the <p> tag in html
$("div#two").after($paragraph);
});
7.4 - removing elements
we have two jQuery functions, `.empty()` and `.remove()`, that help us delete content from our pages.
`.empty()` deletes an element's content and *all its descendants*(子节点). For instance, if you `.empty()` an `'ol'`, you'll also remove all its `'li'`s and their text.
`.remove()`, not only deletes an element's content, but deletes the element itself.
js代码:
1. $(document).ready(function(){
2. $("div#one").after("<p>I'm joined here.</p>");//create a <p> tag after div#one
3. var $paragraph = $("p"); //value the <p>tag into a var for moving
4. $("div#two").after($paragraph); //move the <p> tag after div#two
5. $('p').remove(); //remove the <p>tag
6. });
7.5. Adding and Removing Classes
我们没必要去一个个element的删除修改,可以好好用jQuery的功能来切换class, CSS, and HTML elements.
用 .addClass() 和 .removeClass() 两个函数来完成这个功能。
for example, you have a `highlighted` class that you want to apply to an element when clicked.
The syntax looks like this:
- $(‘selector’).addClass(‘className’);
- $(‘selector’).removeClass(‘className’);
CSS部分代码:
1. .highlighted {
2. -webkit-box-shadow: 0 0 8px #FFD700;
3. -moz-box-shadow: 0 0 8px #FFD700;
4. box-shadow: 0 0 8px #FFD700;
5. cursor:pointer;
6. }
JS部分代码:
1. $(document).ready(function(){
2. $("div#text").click(function(){
3. $(this).addClass('highlighted'); //We've supplied the HTML and CSS
4. });
5. });
7.6 - Toggling Class(推拉Class:点击添加-再点击去掉the class)
如果一个html元素,有了class就给它去掉;没有就给它加上。使用函数:.toggleClass():
$(this).toggleClass('highlighted'); //change the above addClass into toggleClass
7.7 - 修改CSS参数,Chaning your Style
要修改CSS中的参数,比如颜色,对jQuery来说,也是个snap.
- Resize the elements: .width(); .height(); e.g: $(“div”).height(“100px”);
- 对CSS操作:.css e.g.: $(“div”).css(“background-color”,"#008800");
- js示例代码如下
1. $(document).ready(function(){
2. $("div").height(200);
3. $("div").width(200);
4. $("div").css("border-radius","10px");
5. });
7.8 - 修改html内容:modifing content
使用 .html() and .val(); 可以修改html内容,比如:
1. get the HTML contents of the first div it finds:
$('div').html("I love jQuery!");
2. **.val()**
从表单(form)元素中获取值. For example:
1.
2. $('input:checkbox:checked'.val();
would get the value of the first checked checkbox that jQuery finds.
1. $(document).ready(function(){
2. $('p').html("jQuery magic in action!");
3. });
7.9 - 一个html表单及内容添加实例
这里我们要用前面所学的jQuery修改html内容的所有函数来完成一个表单的输入,并显示结果在html页面上。
$(selector for a form).val() – 这里要主要表单的定位方法:‘input[name = formName]’
$(".target").append(’’ + variable + ‘</html tag string>’);
1. $(document).ready(function(){
2. $('#button').click(function(){
3. var toAdd = $('input[name=checkListItem]').val();
4. $(".list").append('<div class="item">' + toAdd + '</div>');
5. });
6. });
对应的html代码:
1. <body>
2. <h2>To Do</h2>
3. <form name="checkListForm">
4. <input type="text" name="checkListItem"/>
5. </form>
6. <div id="button">Add!</div>
7. <br/>
8. <div class="list"></div>
9. </body>
8. $(document).on(); 与 $(document).ready();的区别
在上面的例子中,如果我们想通过单击来去掉通过表单添加的items,我们可能会想到如下的方法:
1.
2. $('.item').click(function() {
3. $(this).remove();
4. });
但是你会发现这个是不work的,因为$(document).ready();执行时,并没有class=item的元素。class=item的元素是click button后,我们添加进html的。
此时就需要用到 $(document).on();函数:
1.
2. $(document).on('event', 'selector', function() {
3. Do something!
4. });
这里我们的 ’event’ = ‘click’, ‘selector’=’.item’ js代码:
1. $(document).ready(function(){
2. $('#button').click(function(){
3. var toAdd = $('input[name=checkListItem]').val();
4. $(".list").append('<div class="item">' + toAdd + '</div>');
5. });
6.
7. $(document).on('click','.item',function(){
8. $(this).remove();
9. });
10. });
You Did It!
Great work! You now know how to dynamically update the content of your HTML page, including adding and removing elements.
Now that you can handle manipulating the DOM on the fly, the hard part is over. In the next two lessons, we’ll cover a wider range of jQuery event handlers and effects, which will allow you to apply your core programming skills to a variety of challenges.
9.复习jQuery的Events
我们已经学了很多关于jQuery events,来复习一下基础的东西。
一般是以下的套路(模板):
1. $(document).ready(function() {
2. $('thingToTouch').event(function() {
3. $('thingToAffect').effect();
4. });
5. });
“thing to touch” is the HTML element you’ll
click on, hover over, or otherwise interact with,
and “thing to affect” is the HTML element that:
fades away, changes size,
or undergoes some other transformation.
我们已经学了很多关于jQuery events,来复习一下基础的东西。
一般是以下的套路:
有时候这些元素是一个或者同样的,你要hover over a
来改变它的不透明度opacity。
有时你要和不同的元素互动,例如你要点击一个button来resize it.
有时候如果你想要一个效果,不要.click 或.hover这样的事件来触发,你可以跳过上面的第二行。
10.总结一下events & actions
10.1 Events:
- .click
- .hover
- .dblclick //double click
- .mouseenter
- .mouseleave
10.2 Actions:
- .fadeOut(‘fast’) //fast, slow, …
- .hide(); //hide
- .slideToggle(‘slow’);
- …
- …
- …..Change styles……
- .addClass()
- .removeClass
下面这个例子是我们常用的鼠标移上来应用一个class,然后移除时候remove that class.
这里在 $(‘div’).hover(A,B);下并排了两个function(){ addClass }, [comma] — function(){ removeClass }, 【中间的逗号很重要!】
1. $(document).ready(function(){
2. $('div' ).hover(
3. function(){
4. $(this).addClass('active');
5. }, //separated by a comma. The comma is very important!
6. function(){
7. $(this).removeClass('active');
8. }
9. );
10. });
实际上.hover(Aaction,Baction);就是这么来的。
11. 响应事件:.focus()
.focus() event 是hover和click都响应的事件,有些html元素可以receive focus。
常见的有
1. <body>
2. <form>
3. Name: <input type='text' name='name'></input>
4. </form>
5. </body>
CSS代码:
1. input {
2. font-family: Verdana, Arial, Sans-Serif;
3. outline-style: solid;
4. }
js代码:
1. $(document).ready(function(){
2. $('input').focus(function(){
3. $(this).css('outline-color','#FF0000');
4. });
5. });
12.the .keydown() event和.animate()效果
当你按下键盘时,移动一个屏幕上的物体。用到.keydown()事件和.animate()效果。
.animate()效果有两个输入:动画和执行时间。比如:
$(‘div’).animate({left:’+=10px’},500); //.animate({ },100);
This will take the first div it finds and move it ten pixels to the right.
1. $(document).ready(function(){
2. $(document).keydown( function(){<span style="white-space:pre"> </span>//我还怀疑要用 $(document).on();哟
3. $('div').animate({left:'+=10px'},500);
4. });
5. });
6. /***** General Model:
7. * $(document).ready(function() {
8. * $(document).event(function() {
9. * $('div').effect(anim, duration);
10. * });
11. * });
12. */
在看一个更高级的例子:
1. $(document).ready(function() {
2. $(document).keydown(function(key) {
3. switch(parseInt(key.which,10)) {
4. // Left arrow key pressed
5. case 37:
6. $('img').animate({left: "-=10px"}, 'fast');
7. break;
8. // Up Arrow Pressed
9. case 38:
10. // Put our code here
11. $('img').animate({top: "-=10px" }, 'fast');
12. break;
13. // Right Arrow Pressed
14. case 39:
15. // Put our code here
16. $('img').animate({left: "+=10px"}, 'fast');
17. break;
18. // Down Arrow Pressed
19. case 40:
20. // Put our code here
21. $('img').animate({top: "+=10px"}, 'fast');
22. break;
23. }
24. });
25. });
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
13. jQuery UI
jQuery UI 是个神马东东? jQuery UI是个new jQuery Library. jQuery UI includes a number of ultra-fancy animations you can use to make your websites do incredible things.
For instance, remember when we lamented that jQuery didn’t include a .blowUp()
effect for our planet Krypton? Well, that’s still true. But jQuery UI has an.effect()
effect, and we are totally going to give it the input'explode'
.
注意我们include了一个新的script标签,html代码如下:
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
比如,然后我们就可以用.effect()函数作为一个effect然后输入’explode’作为参数来定义一个动画效果:
1. $(document).ready(function(){
2. $('div').click(function(){
3. $(this).effect('explode');
4. });
5. });
另一个效果: bounce(弹起),弹起2次in 900 milliseconds:
1. $(document).ready(function(){
2. $('div').click(function(){
3. //bounce twice in 900 milliseconds:
4. $(this).effect('bounce',{times:2},900);
5. });
6. });
再来一个效果: slide: (从左至右滑入)
1. $(document).ready(function(){
2. $('div').click(function(){
3. $(this).effect('slide');
4. });
5. });
The **.effect()**
effect has all kinds of magical goodness in it, but it’s not the most amazing thing jQuery UI can do. The library has a number of built-in effects that can make your website look sleek and professional with surprisingly little code.
jQuery除了.effect()还有很多更专业的效果且占用很少代码,你可以看下面的documentation了解更多:
You can learn more in the jQuery UI documentation!
14.一个使用jQuery UI做成的下拉菜单效果
Html:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Behold!</title>
5. <link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css'/>
6. <script type='text/javascript' src='script.js'></script>
7. <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
8. </head>
9. <body>
10. <div id="menu">
11. <h3>jQuery</h3>
12. <div>
13. <p>jQuery is a JavaScript library that makes your websites look absolutely stunning.</p>
14. </div>
15. <h3>jQuery UI</h3>
16. <div>
17. <p>jQuery UI includes even more jQuery goodness!</p>
18. </div>
19. <h3>JavaScript</h3>
20. <div>
21. <p>JavaScript is a programming language used in web browsers, and it's what powers jQuery and jQuery UI. You can learn about JavaScript in the <a href="http://www.codecademy.com/tracks/javascript" target="blank" style="text-decoration:none; color:#F39814">JavaScript track</a> here on Codecademy.</p>
22. </div>
23. </div>
24. </body>
25. </html>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
javascript:
1. $(document).ready(function() {
2. $("#menu").accordion({collapsible: true, active: false});
3. });
15.jQuery UI 中几个效果函数
.draggable()允许你拖动任何一个元素,把它放在任何地方:
.resizable()允许你改变横向大小: $(‘div’).resizable();
16.jQuery UI还能有更牛的selector
下面这个html的list有点bland(乏味),来看我们怎么用jQuery UI来优化一下:
1. <body>
2. <ol>
3. <li>Super Mario Bros.</li>
4. <li>Tetris</li>
5. <li>Legend of Zelda: Link's Awakening</li>
6. <li>Kirby's Dream World</li>
7. <li>Burger Time</li>
8. <li>Pokémon Red</li>
9. <li>Pokémon Blue</li>
10. </ol>
11. </body>
CSS:
1. ol {
2. <span style="white-space:pre"> </span>list-style-type: none;
3. position: relative;
4. left: -20px;
5. }
6.
7. ol li {
8. background: #eeeeee;
9. border-radius: 5px;
10. border: 1px solid black;
11. margin: 3px;
12. padding: 0.4em;
13. font-size: 1em;
14. height: 16px;
15. font-family: Verdana, Arial, Sans-Serif;
16. }
17.
18. ol .ui-selected {
19. background: #F39814; color: white;
20. }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
js:
1. $(document).ready(function(){
2. $('ol').selectable(); //enable the css effect ".ui-selected"
3. //$('ol').sortable();//click and rearrange your list items as you like!
4. });
这里引入了2个对
- 操作的methods: .selectable() & .sortable()
17. jQuery 里 .accordion() 方法,注意不是according
我们要实现accordion-style dropdown menu了,用.accordion()函数。First, however, we’ll need some additional HTML elements.
HTML:
1. <body>
2. <div id="menu">
3. <h3>Section 1</h3>
4. <div>
5. <p>I'm the first section!</p>
6. </div>
7. <!--Add two more sections below!-->
8. <h3>Section 2</h3>
9. <div>
10. <p>I'm the second section!</p>
11. </div>
12. <h3>Section 3</h3>
13. <div>
14. <p>I'm the third section!</p>
15. </div>
16. </div>
17. </body>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
js:
1. $(document).ready(function(){
2. $('#menu').accordion();
3. });
好了,你已经搞定了。别忘了jQueryUI使用时,要添加 comments powered by Disqus