jQuery学习笔记1

关飞翼
2023-12-01

开始之前: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的基本骨架代码

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div id="red" ></div>
    </body>
</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:

$() says, "hey, jQuery things are about to happen!"是把()内的东东转化成jQuery的object,从而有后面的.ready这个method
Putting document between the parentheses tells us that we're about to work our magic on the HTML document itself.
.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!"
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

$(document).ready(
    function(){
        $('div').mouseenter(
            function(){
            $('div').fadeTo('fast',1);    
            }
        );
        $('div').mouseleave(
            function(){
            $('div').fadeTo('fast',0.5)
            }  
        );
    }
);


这个就是先(document)ready , 然后(div)mouseenter,最后(div)fadeTo.

实际上这个排版不是很通用,通用的排版应该是:

$(document).ready(function(){
    $('div').mouseenter(function(){
        $('div').fadeTo('fast',1);    
    });
    $('div').mouseleave(function(){
        $('div').fadeTo('fast',0.5)
    });
});


4.关于CSS中的selector

在有列表情况下,如果想通过js对列表中的某一项进行操作,需要用到selector来指定是修改哪一个:比如:

<ol>
   <li>Start with the function keyword</li>
   <li>Inputs go between ()</li>
   <li>Actions go between {}</li>
   <li id="no4" class="hide">jQuery is for chumps!</li>
</ol>

这个html列表,我们jQuery可以用CSS的这4种方法来指明:

  • id
  • class
  • nth-child(n)
  • last-child

// Write your jQuery code on line 3!
$(document).ready(function() {
    var $target = $('li#no4')   //use an id or class
    //var $target = $('li.hide')    //use a class
    //var $target = $('li:nth-child(4)') //use "nth-child(n)"
    //var $target = $('li:last-child')  //use "last-child"
    $target.fadeOut('fast');
});

  另外,需要同时定位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来让它消失:
$(document).ready(function() {
    $('div').click(function() {
        $(this).fadeOut('slow'); //对上次事件的对象进行fadeOut操作
    });
});
原html部分代码如下:
<body>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
</body>

6.关于Toggling Our Panel的实例

本实例要实现点击下拉一个div出来的效果,先用display:none在CSS中将div隐藏,再在js中调用jQuery的slideToggle()函数:
部分html代码如下:
    <body>
        <div class="panel">
        <br />
        <br />
        <p>Now you see me!</p>
        </div>
        <p class="slide"><div class="pull-me">Slide Up/Down</div></p>
    </body>


全部CSS代码如下:
body {
    margin:0 auto;
    padding:0;
    width:200px;
    text-align:center;
}
.pull-me{
    -webkit-box-shadow: 0 0 8px #FFD700;
    -moz-box-shadow: 0 0 8px #FFD700;
    box-shadow: 0 0 8px #FFD700;
    cursor:pointer;
}
.panel {
    background: #ffffbd;
    background-size:90% 90%;
    height:140px;
    display:none;  /*there we go*/
    font-family:garamond,times-new-roman,serif;
}
.panel p{
    text-align:center;
}
.slide {
    margin:0;
    padding:0;
    border-top:solid 2px #cc0000;
}
.pull-me {
    display:block;
    position:relative;
    right:-25px;
    width:150px;
    height:20px;
    font-family:arial,sans-serif;
    font-size:14px;
    color:#ffffff;
    background:#cc0000;
    text-decoration:none;
    -moz-border-bottom-left-radius:5px;
    -moz-border-bottom-right-radius:5px;
    border-bottom-left-radius:5px;
    border-bottom-right-radius:5px;
}
.pull-me p {
    text-align:center;
}


全部js代码如下:
$(document).ready(function(){
    $('.pull-me').click(
        function(){
        $('.panel').slideToggle('slow');
    });
});
到这里就掌握了基本的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("<p>Stuff!</p>");//inserts element as the last child of the target
	$(".info").prepend("<p>Stuff!</p>"); //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示例代码:

    <body>
        <div class="container">
            <h2>Greetings</h2>
            <div id="one">Div #1</div>
            <div id="two">Div #2</div>
        </div>   
    </body>

js代码:

$(document).ready(function(){
    $("div#one").after("<p>I'm joined here.</p>");
});

    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代码:

$(document).ready(function(){
    $("div#one").after("<p>I'm joined here.</p>");//create a <p> tag after div#one
    var $paragraph = $("p");    //value the <p>tag into a var for moving
    $("div#two").after($paragraph); //move the <p> tag after div#two
    $('p').remove();    //remove the <p>tag
});

    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部分代码:

.highlighted {
    -webkit-box-shadow: 0 0 8px #FFD700;
    -moz-box-shadow: 0 0 8px #FFD700;
    box-shadow: 0 0 8px #FFD700;
    cursor:pointer;
}

JS部分代码:

$(document).ready(function(){
    $("div#text").click(function(){
        $(this).addClass('highlighted'); //We've supplied the HTML and CSS
    });
});

    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示例代码如下
$(document).ready(function(){
    $("div").height(200);
    $("div").width(200);
    $("div").css("border-radius","10px");
});

    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:


      $('input:checkbox:checked'.val();
       would get the value of the first checked checkbox that jQuery finds.
$(document).ready(function(){
    $('p').html("jQuery magic in action!");
});
    7.9 - 一个html表单及内容添加实例

        这里我们要用前面所学的jQuery修改html内容的所有函数来完成一个表单的输入,并显示结果在html页面上。
        $(selector for a form).val()   -- 这里要主要表单的定位方法:'input[name = formName]'
        $(".target").append('<html tag string>' + variable + '</html tag string>');

$(document).ready(function(){
    $('#button').click(function(){
        var toAdd = $('input[name=checkListItem]').val();
        $(".list").append('<div class="item">' + toAdd + '</div>');
    });
});

对应的html代码:

	<body>
		<h2>To Do</h2>
		<form name="checkListForm">
			<input type="text" name="checkListItem"/>
		</form>
		<div id="button">Add!</div>
		<br/>
		<div class="list"></div>
	</body>


8. $(document).on(); 与 $(document).ready();的区别

    在上面的例子中,如果我们想通过单击来去掉通过表单添加的items,我们可能会想到如下的方法:


  $('.item').click(function() {
     $(this).remove();
  });
   但是你会发现这个是不work的,因为$(document).ready();执行时,并没有class=item的元素。class=item的元素是click button后,我们添加进html的。
   此时就需要用到 $(document).on();函数:

  $(document).on('event', 'selector', function() {
     Do something!
  });
   这里我们的 'event' = 'click', 'selector'='.item'

   js代码:

$(document).ready(function(){
    $('#button').click(function(){
        var toAdd = $('input[name=checkListItem]').val();
        $(".list").append('<div class="item">' + toAdd + '</div>');
    });
    
    $(document).on('click','.item',function(){
        $(this).remove();   
    });
});

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,来复习一下基础的东西。
一般是以下的套路(模板):
  $(document).ready(function() {
    $('thingToTouch').event(function() {
        $('thingToAffect').effect();
    });
  });
"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 }, 【中间的逗号很重要!】
$(document).ready(function(){
  $('div' ).hover(
    function(){
        $(this).addClass('active');
    },  //separated by a comma. The comma is very important!
    function(){
        $(this).removeClass('active');
    }
  );
});
实际上.hover(Aaction,Baction);就是这么来的。

11. 响应事件:.focus()

.focus() event 是hover和click都响应的事件,有些html元素可以receive focus。
常见的有<textarea>s and <input>.
这个例子是要让highlight变成红色。
我们可以用css和.focus()来搞,We want to write a bit of jQuery code that will change our 'input''s 'outline-color' to 'red' when it gains focus.
html代码:

	<body>
		<form>
			Name: <input type='text' name='name'></input>
		</form>
	</body>
CSS代码:
    input {
        font-family: Verdana, Arial, Sans-Serif;
        outline-style: solid;
    }
js代码:
$(document).ready(function(){
    $('input').focus(function(){
        $(this).css('outline-color','#FF0000');
        });
    });

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.

$(document).ready(function(){
    $(document).keydown( function(){<span style="white-space:pre">		</span>//我还怀疑要用 $(document).on();哟
        $('div').animate({left:'+=10px'},500);
    });
});
/***** General Model:
* $(document).ready(function() {
*   $(document).event(function() {
*     $('div').effect(anim, duration);
*   });
* });
*/

在看一个更高级的例子:

$(document).ready(function() {
    $(document).keydown(function(key) {
        switch(parseInt(key.which,10)) {
			// Left arrow key pressed
			case 37:
				$('img').animate({left: "-=10px"}, 'fast');
				break;
			// Up Arrow Pressed
			case 38:
				// Put our code here
				$('img').animate({top: "-=10px" }, 'fast');
				break;
			// Right Arrow Pressed
			case 39:
				// Put our code here
				$('img').animate({left: "+=10px"}, 'fast');
				break;
			// Down Arrow Pressed
			case 40:
				// Put our code here
				$('img').animate({top:  "+=10px"}, 'fast');
				break;
		}
	});
});

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'作为参数来定义一个动画效果:
$(document).ready(function(){
    $('div').click(function(){
        $(this).effect('explode');
        });
    });
另一个效果: bounce(弹起),弹起2次in 900 milliseconds:
$(document).ready(function(){
    $('div').click(function(){
        //bounce twice in 900 milliseconds:
        $(this).effect('bounce',{times:2},900);
        });
    });
再来一个效果: slide: (从左至右滑入)
$(document).ready(function(){
    $('div').click(function(){
        $(this).effect('slide');
        });
    });

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:

<!DOCTYPE html>
<html>
    <head>
    	<title>Behold!</title>
        <link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css'/>
        <script type='text/javascript' src='script.js'></script>
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
	</head>
	<body>
        <div id="menu">
            <h3>jQuery</h3>
            <div>
                <p>jQuery is a JavaScript library that makes your websites look absolutely stunning.</p>
            </div>
            <h3>jQuery UI</h3>
            <div>
                <p>jQuery UI includes even more jQuery goodness!</p>
            </div>
            <h3>JavaScript</h3>
            <div>
                <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>
            </div>
        </div>
	</body>
</html>

javascript:

$(document).ready(function() {
    $("#menu").accordion({collapsible: true, active: false});
});

15.jQuery UI 中几个效果函数

      .draggable()允许你拖动任何一个元素,把它放在任何地方:
      .resizable()允许你改变横向大小:     $('div').resizable();

16.jQuery UI还能有更牛的selector

下面这个html的list有点bland(乏味),来看我们怎么用jQuery UI来优化一下:

	<body>
        <ol>
            <li>Super Mario Bros.</li>
            <li>Tetris</li>
            <li>Legend of Zelda: Link's Awakening</li>
            <li>Kirby's Dream World</li>
            <li>Burger Time</li>
            <li>Pokémon Red</li>
            <li>Pokémon Blue</li>
        </ol>   
	</body>
CSS: 
    ol {
<span style="white-space:pre">	</span>list-style-type: none;
	position: relative;
	left: -20px;
    }

    ol li {
	background: #eeeeee;
	border-radius: 5px;
	border: 1px solid black;
	margin: 3px;
	padding: 0.4em;
	font-size: 1em;
	height: 16px;
	font-family: Verdana, Arial, Sans-Serif;
    }

    ol .ui-selected {
	background: #F39814; color: white;
    }
js:
$(document).ready(function(){
    $('ol').selectable(); //enable the css effect ".ui-selected"
    //$('ol').sortable();//click and rearrange your list items as you like!
    });

这里引入了2个对<ol>操作的methods:  .selectable() & .sortable()

17. jQuery 里 .accordion() 方法,注意不是according

我们要实现accordion-style dropdown menu了,用.accordion()函数。First, however, we'll need some additional HTML elements.

HTML:

	<body>
        <div id="menu">
            <h3>Section 1</h3>
            <div>
                <p>I'm the first section!</p>
            </div>
            <!--Add two more sections below!-->
            <h3>Section 2</h3>
            <div>
                <p>I'm the second section!</p>
            </div>
            <h3>Section 3</h3>
            <div>
                <p>I'm the third section!</p>
            </div>
        </div>
	</body>
js:
$(document).ready(function(){
    $('#menu').accordion();
    });
好了,你已经搞定了。别忘了jQueryUI使用时,要添加<script>标签支持jQuery UI 的Library.

Summary

JavaScriptis a programming language used to add interactivity to a web page.jQuerysimplifies JavaScript syntax and makes it easier to build interactive web pages that work across multiple browsers.

jQuery enables us to do three main things on a web page:

  1. Events.Respond to user interactions.

  2. DOM Manipulation.Modify HTML elements on the page.

  3. Effects.Add animations.

We'll see how to do each of these things in the next sections.



 类似资料: