1. Overview of jQuery
The concept of jquery
jQuery is a fast and concise JavaScript library.
jQuery encapsulates the functional codes commonly used in JavaScript, optimizes DOM operations and event processing. Animation Design and Ajax Interaction
advantage
- Lightweight, the core file is only tens of kb, it will not affect the loading speed of the page
- cross-browser compatible
- chained programming, implicit iteration
- Support for events, styles, and animations greatly simplifies DOM operations
- Support plug-in expansion development, with a wealth of third-party plug-ins, such as: tree menu, date control, carousel, etc.
- free, open source
Second, the basic use of jQuery
1. jquery download
Official website address: http://jquery.com/
2. The entry function of jQuery
$(function (){
})
$(document).ready(function(){
}})
- After the DOM is loaded, execute the js code
- Equivalent to DOMContentLoaded in native js'
3. jQuery's top-level object $
- $ is another name for jQuery
- $ is also jQuery's top-level object
jQuery objects and DOM objects
- The object obtained with native js is the DOM object
- The element obtained by the jQuery method is the jQuery object.
The essence: the object generated by wrapping the DOM object with $ (storage in the form of a pseudo-array)
Note that
jQuery can only use jQuery objects, and DOM objects can only use native JavaScript properties and methods
mutual conversion
- DOM object converted to jQuery object
$(DOM object)
- Convert jQuery object to DOM object
$('div')[index] (index is the index number)
$('div').get(index) (index is the index number)
Three, jQuery common API
1. jQuery selector: $("selector")
base selector
Selector | grammar | illustrate |
---|---|---|
ID selector | $(“#id”) | Get the element with the specified id |
select all selector | $(“*”) | matches all elements |
class selector | $(" .class") | Get elements of the same class |
label selector | $(" div ") | Get all elements of the same tag |
union selector | $(" div,p,li ") | get multiple elements |
intersection selector | $(" li.current ") | intersection selector |
level selector
Selector | grammar | illustrate |
---|---|---|
child selector | $(" ul>li ") | Use the > sign to get the elements of the parent-child level; note that the elements of the grandchild level will not be obtained |
descendant selector | $(" ul li ") | Use spaces to represent descendant selectors to get all li elements under ul, including grandchildren, etc. |
filter selector
Selector | grammar | illustrate |
---|---|---|
:first | $(" li:first" ) | Get the first li element |
:last | $(" li:last" ) | Get the last li element |
:eq(index) | $(" li:eq(0) ") | Among the obtained elements, select the element whose index number is 0, and the index number starts from 0 |
:odd | $(" li:odd" ) | Among the obtained elements, select the element whose index number is odd |
:even | $(" li:even" ) | Among the obtained elements, select the element whose index number is even |
screening method
method | grammar | illustrate |
---|---|---|
parent() | $(“li”).parent(); | find parent |
chuildren(selector) | $(“ul”).children(“li”) | Equivalent to $("ul>li"), the nearest level (pro son) |
find(selector) | $(“ul”).find(“li”) | Equivalent to $("ul li"), descendant selector |
siblings(selector) | $(“.first”).siblings(“li”) | Find sibling nodes, not including itself |
nextAll([expr]) | $(“.first”).nextAll() | Find all sibling elements after the current element |
prevAll([expr]) | $(“.first”).prevAll() | Find all sibling elements before the current element |
hasClass(class) | $(“div”).hasClass(“protected”) | Checks if the current element contains a specific class, and returns true if it does |
eq(index) | $(“li”).eq(2); | Equivalent to $("li:eq(2)"), index starts from 0 |
implicit iteration
Loop through all the matched elements and execute the corresponding method instead of looping again, simplifying our operations and making it easy for us to call
chain programming
save code
$(this).css(“color”,“red”).sibling().css(“color”.“”)
2. jquery style operation
Operation css method
- The parameter only writes the attribute name, and returns the attribute value
$(this).css(“color”)
- The parameter is attribute name, attribute value, separated by commas, is to set a set of styles, the attribute must be quoted, if the value is a number, it does not need to follow the unit and guide
$(this).css(" color",“red”)
- Parameters can be in the form of objects, which is convenient for setting multiple sets of styles. The attribute name and attribute value are separated by a colon, and the attribute does not need to be quoted
$(this).css({“color”:“red”,“fontSize“:”20px”})
set class style method
The effect is equivalent to classList
- add class
$(“div”).addClass(“current”);
- remove class
$(“div”).remove(“current”);
- switch class
$(“div”).toggleClass(“current”);
3. jQuery animation
(1) Show hidden effects
display effect
show([ speed ,[easing],[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
hide syntax effects
hide([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
transition effect
toggle([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
(2) Slide effect
display effect
slideDown([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
hidden effect
slideUP([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
transition effect
slideTaggle([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
event switching
hover([over],out)
$(" . nav>li") . hover(function() {
}, function() {
})
- over: the function to be triggered when the mouse moves over the element (equivalent to mouseenter)
- out: the function to be triggered when the mouse moves out of the element (equivalent to mouseleave)
- Over can be omitted
The animation queue and its dequeue method
animation or effects queue
Once the animation or effect is triggered, it will be executed. If it is triggered multiple times, multiple animations or effects will be queued for execution.
stop queuing
stop()
The stop() method is used to stop the animation or effect
Note: stop() is written in front of the animation or effect, which is equivalent to stopping the last animation
(3) Fade in and fade out effect
fade in effect
fadeIn([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
fade out effect
fadeOut([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
transition effect
fadeToggle([ speed, [easing] ,[fn]])
- The parameter can be omitted, and it will be displayed directly without animation
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
fadeTo([ speed, opacity, [easing] ,[fn]])
- opacity Transparency must be written, value between 0 and 1 must be written
- speed: A character string of one of three predetermined speeds (slow normal fast) or a millisecond value representing the duration of the animation (eg: 1000) must be written
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
(4) Custom animation animate
animate([ params,[speed], [easing] ,[fn]])
- params: The style attribute to be changed , passed as an object, must be written . The attribute name can be used without quotation marks. If it matches the attribute, it needs to be named in camel case
- speed: A string of one of three predetermined speeds (slow normal fast) or a value in milliseconds representing the duration of the animation (eg: 1000)
- easing: (Optional) used to specify the switching effect, the default is "swing", the available parameter "linear"
- fn: callback function, the function executed when the animation is completed, executed once for each element
Accordion case
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>手风琴案例</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
img {
display: block;
}
ul {
list-style: none;
}
.king {
width: 852px;
margin: 100px auto;
background: url(images/bg.png) no-repeat;
overflow: hidden;
padding: 10px;
}
.king ul {
overflow: hidden;
}
.king li {
position: relative;
float: left;
width: 69px;
height: 69px;
margin-right: 10px;
}
.king li.current {
width: 224px;
}
.king li.current .big {
display: block;
}
.king li.current .small {
display: none;
}
.big {
width: 224px;
display: none;
}
.small {
position: absolute;
top: 0;
left: 0;
width: 69px;
height: 69px;
border-radius: 5px;
}
</style>
<script src="js/jquery-3.6.0.min.js"></script>
<script>
$(function () {
$(".king li").mouseenter(function () {
$(this).stop().animate({
width: 224
}).find(".small").stop().fadeOut().siblings(".big").stop().fadeIn();
$(this).siblings().stop().animate({
width: 69
}).find(".small").stop().fadeIn().siblings(".big").stop().fadeOut();
})
})
</script>
</head>
<body>
<div class="king">
<ul>
<li class="current">
<a href="#">
<img src="images/m1.jpg" alt="" class="small">
<img src="images/m.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/l1.jpg" alt="" class="small">
<img src="images/l.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/c1.jpg" alt="" class="small">
<img src="images/c.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/w1.jpg" alt="" class="small">
<img src="images/w.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/z1.jpg" alt="" class="small">
<img src="images/z.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/h1.jpg" alt="" class="small">
<img src="images/h.png" alt="" class="big">
</a>
</li>
<li>
<a href="#">
<img src="images/t1.jpg" alt="" class="small">
<img src="images/t.png" alt="" class="big">
</a>
</li>
</ul>
</div>
</body>
</html>
3. jQuery property manipulation
Set or get the element's intrinsic attribute value prop()
Obtain
prop("property")
set properties
prop("property", "property value")
Set or get the element's custom attribute value attr()
get attribute
attr("attribute")
is similar to native getAttribute()
set properties
attr("attribute", "attribute value")
setAttribute()
data cache data()
The data() method can access data on the specified element, and will not modify the DOM element structure
Additional data syntax
- data("name", "value")
appends data to the selected element
get data syntax
- data(''name'')
gets data from the selected element
You can also read the HTML5 custom attribute data-index, and the result is a number
4. jQuery content text value
Ordinary elements get content html() (equivalent to native innerHTML)
- html() to get element content
- html("content") sets element content
Common element text content text() (equivalent to native innerHText)
- text() gets the text content of the element - text("text content") sets the text content of the element
input form to get content
- val() gets form content
- val "content") sets the form text content
Other methods
- parents("selector") returns ancestor elements
- toFixed(2) retains 2 decimal places
- substr(1) intercepts a string
5. jQuery element manipulation
traverse elements
Perform different operations on the same type of elements
$("div").each(function(index ,domEle){
xxx; } )
$.each(arr,function(){
})
- The each() method traverses each matching element, mainly using DOM processing
- The callback function inside has 2 parameters: index is the index number of each element; domEle is each DOM element object, not a jQuery object
- dom elements need to be converted to jQuery objects $(donEle)
create element
Dynamically created a li
$("<li></li>");
add element
Add internally
Add internally and put it at the end
$("ul").append(li);
Added internally and placed at the front
$("ul").prepend(li);
External addition puts the content behind
the target element
$("div").after("内容")
Put the content before the target element
$("div").before("内容")
- After the internal added elements are generated, they are parent-child relationships
- After the externally added elements are generated, they are sibling elements
delete element
remove the matching element (itself)
$("div").remove()
Delete all child nodes in the matching element set
$("div").empty()
Empty the matched element content
$("div").html("")
6. jQuery size, position operation
jQuery-size
Attributes | illustrate |
---|---|
width()/height() | Get the width and height of the matched element, only width/height |
innerWidth()/innerHeight() | Get the width and height of the matched element, including padding |
outerWidth()/outerHeight() | Get the width and height of the matched element, including padding and border |
outerWidth(true)/outerHeight(true) | Get the width and height of the matching element, including padding and border, margin |
overview
- If the above parameters are empty, get the corresponding value and return a numeric value
- If the parameter is a number, modify the corresponding value
- The parameter can not write the unit
jQuery position
offset()
Set and get element offset
offset() method sets or returns the offset coordinates of the selected element relative to the document, and has no relationship with the parent
attribute
Attributes | use | illustrate |
---|---|---|
top | offset().top | Used to get the distance from the top of the document |
left | offset().left | Used to get the distance from the left side of the document |
The offset of the element can be set: offset({top: 10, left: 29})
position()
Get the position of the element relative to the parent element with positioning . If the parent is not positioned, the document shall prevail. It can only be obtained and cannot be set.
scrollTop()/scrollLeft()
- Set the head and left side of the element being rolled away
- There is a scrollTop attribute in the animate animation function, which can set the position
- But the element is animated, so $(. "body,html").animate({scrollTop: 0})
7. jQuery event
jQuery event registration
$("div").click(function(){
事件处理程序})
与原生基本一致:mouseover、mouseout、bliur、focus等
jQuery事件处理
on()事件绑定
on()方法在匹配元素上绑定一个或多个事件的事件处理函数
element.on(events,[selector],fn)
- events:一个或多个用空格分隔的事件类型,如“click”或“keydown”
- selector:元素的子元素选择器
- fn:回调函数,即绑定在元素身上的侦听函数
- 利用对象的方式绑定多个事件
优势
-
可以绑定多个事件,多个处理事件处理程序
$ ("div") .on({ mouseover: function() { }, mouseout: function() { }, click: function() { } }) ;
如果事件处理程序相同
$ ("div") . on ("mouseover mouseout", function() { $ (this) . tqggleClass ("current"); }) ;
-
可以事件委派操作,事件委派的定义就是,把原来加给子元素身上得到事件绑定在父元素身上,就是把事件委派给父元素
$('ul') .on('click', 'li', function() { alert( 'hello world!') ; }) ;
-
on可以给未来动态创建的元素绑定事件
off()事件解绑
off()方法可以移除通过on()方法添加的事件处理程序
$("p").off() //解绑怕元素所有事件处理程序
$("p").off("click") //解绑p元素上面的点击事件
$("ul").off(""click","li"); //解绑事件委托
如果有的事件只想执行触发一次,可以使用one()来绑定事件
自动触发事件trigger()
1. $("div").click();元素.事件()
2. $("div").trigger("click")
不会触发元素的默认行为
3. $("div").triggerHandler("click")
jQuery事件对象
element.on(events,[selector],function(event){
})
阻止默认行为
event.preventDefault() 或者 return false
阻止冒泡行为
event.stopPropagation()
jQuery其他事件
jQuery拷贝对象
把某个对象拷贝(合并)给另外一个对象使用,可以使用$.extend()方法
$.extend([deep],target,object1,[objectN])
- deep: 如果设为true为深拷贝,默认为false 浅拷贝
- Shallow copy: It is to give the address in the complex data type of the copied object to the target object, and modifying the target object will affect the copied object
- Deep copy: Add true in front, complete clone (copied object, not address), modifying the target object will not affect the copied object
- target: the target object to copy
- object1: the object to be copied to the first object
Coexistence of multiple libraries
Problem Overview
jQuery uses $ as an identifier. With the popularity of jQuery, other js libraries will also use $ as an identifier. Using it together will cause conflicts.
Objective requirements
make jQuery and other js libraries do not conflict, can exist at the same time, called multi-library coexistence
solution
- Change the $ sign inside to agree to jQuery
- The jQuery variable specifies the new name
$.noConflict()
var xx = $.noConflict();
Plugins for jQuery
Websites commonly used by jQuery plugins
- jQuery plugin library
http://www.jq22.com/ - Home of jQuery
http://www.htmleaf.com/
Steps to use the jQuery plugin
- Import related files. (jquery file and plugin file)
- Copy related html, css, js (call plug-in)