Entry function
/*js Load completion event*/ window.onload=function(){ console.log("Pages and resources are fully loaded"); } /*jQuery ready function of*/ $(document).ready(function(){ console.log("page dom Layer rendering complete---I write it completely"); }); $(function(){ console.log("page dom Layer rendering complete---I'm short for situation"); });
- The difference between the onload event and the ready function is that the execution timing is different Onload needs to load all the resources loaded on the dom layer of the page and the page before executing the ready function. It only needs to be executed after rendering on the dom layer. It doesn't care whether the resources are loaded or not, and the execution times are different Only one onload function is valid in the page. If there are multiple onload functions, the latter will overwrite the former. There can be multiple ready functions in the page, which are executed in order
Conversion of jQuery object and DOM object
JQuery object is a pseudo array composed of DOM objects. JQuery to DOM uses the array value method, and DOM to jQuery uses the jQuery factory function.
//Get jq object let div=$("div"); //Get DOM object by array value let divDom=div[0]; //Get function to get DOM object let divDom=div.get(0); //Get DOM object let box=document.getElementById("box"); //Factory function conversion using jq /*Generally, when a converted jq object or a self created jq object is named, it is recommended to start with $*/ let $box=$(box);
jQuery selector (same as CSS selector)
JQuery selectors are exactly the same as CSS1-3 selectors, but jQuery selectors are better in compatibility. For example, the selector of CSS3 cannot be used in IE8 and below browsers, but it can be used in JQ. The versions below jq1.7 can be used in IE8, so it indirectly implements the selector using CSS3 in IE8.
Basic selector
- Wildcard selector
- ID Selector
- Class selector
- tag chooser
- Intersection selector
- Union selector
Level selector
- Descendant selector (equivalent to children function)
- Descendant selector (equivalent to find function)
//Use selectors to implement descendant selection $("div p").css("color","red"); //Use the find function to select descendants $("div").find("p").css("color","red"); //Using selectors to select children $("div>p").css("color","red"); //Children function is used to select children $("div").children("p").css("color","p");
Filter selector
//Select the li with subscript 0 in all matching li $("li:eq(0)").css("color","red"); //The corresponding function is eq function $("li").eq(0).css("color","red"); //Gets the li with odd subscript in all matched li $("li:odd").css("color","red"); //Gets the li with even subscript in all matched li $("li:even").css("color","red");
jQuery selector common functions
Function name | explain |
children(selector) | Equivalent to the descendant selector. If no parameter is given (equivalent to *), it means that all descendants are obtained |
find(selector) | Equivalent to descendant selector, no parameters are given as above |
eq(index) | Match the one with index in the resulting set of elements |
siblings(selector) | Find sibling nodes other than yourself. If you don't give parameters, find all. |
next(selector) | Find the next sibling node. If a parameter is given and the next node does not meet the parameter requirements, it will not be selected. Generally, the parameter is not given |
prev(selector) | Find the previous sibling node. If a parameter is given and the previous node does not meet the parameter requirements, it will not be selected. Generally, the parameter is not given |
parent() | Get parent node |
parents(selector) | Gets the first level of all parent nodes that meet the given parameter requirements |
jQuery operation properties
- The difference between attr and prop prop prop can be used in jQuery after version 1.7, and all versions of attr can be used after version 1.7. It is recommended to use prop function to operate attributes with Boolean attribute values, such as checked, selected, readonly, etc. Attr can manipulate any attribute (including custom attributes), and prop can only manipulate native attributes
- When attr and prop obtain and operate values, only the corresponding attributes of the first element are obtained in the matched elements. Setting is to set the attributes of all the matched elements
//Get the native attribute -- the results of attr and prop are the same console.log($("div").attr("title")); console.log($("div").prop("title")); //Gets a property with the same property value and property name console.log($("input").attr("checked")); //The selected result is checked, otherwise undefined console.log($("input").prop("checked")); //The selected result is true, otherwise false //Get custom properties console.log($("div").attr("zdy")); //It can be taken normally console.log($("div").prop("zdy")); //The result is undefined //Set native properties $("div").attr("title","attr Set the title of the"); //Can set $("div").prop("title","prop Set the title of the"); //Can set //Set a property with the same property name and property value $("input").attr("checked",true); //Set selected $("input").attr("checked","checked"); //Setting is selected. Before version 1.7, only attr settings can be used. This scheme is recommended $("input").attr("checked",false); //Set unchecked //Uncheck before version 1.7 $("input").removeAttr("checked"); //Set unchecked $("input").prop("checked",true); //Set selected $("input").prop("checked",false); //Set unchecked //Set custom properties $("div").attr("zdy2","Custom 2"); //You can set properties $("div").prop("zdy2","Custom 2"); //The setting property is invalid //Set multiple properties at once $("div").attr({title:"Multiple attributes at a time",id:"d1"}); //The method of transferring objects in attr function is the same as that of batch setting attributes / prop function
jQuery operation style
Action inline style (css)
- The operation of css function is basically the same as that of attr function. css function directly sets the style attribute in the tag.
- When css function is set, all matched elements are set, and only the value of the first matched element is obtained
//Set text color $("p").css("color","red"); //Set background color: the background color property is to be overwritten with backgroundColor $("p").css("backgroundColor","green"); //Set multiple styles at once $("p").css({color:"red",fontSize:"20px"}); //Gets the value of the style console.log($("p").css("fontSize"));
Operation class
- Append style
//Append a style $("p").addClass("active"); //Append multiple styles, separated by spaces $("p").addClass("active hover");
- Remove style
$("div").removeClass("active");
- Judgment style
let flag=$("p").hasClass("active"); console.log(flag); //If the p tag has an active style, the result is true; otherwise, it is false
- Toggle style
//If the p label has an active style, the style is removed; otherwise, the active style is appended $("p").toogleClass("active");
jQuery operation DOM
Create DOM
Using the jQuery factory function, you can directly create the DOM node of the jQuery object
let $p=$("<p title="Move your mouse away~~">I am jq Created label</p>"); //At this time, the dom object $p exists only in memory, and the element does not exist in the page console.log($p);
Add DOM
- Add to the inner end of the selected label //$ The p element is appended to the inner end of the box's label
$("#box").append($p);
//This code is equivalent to append, but the caller has changed
//$p.appendTo($("#box")); - Add to the inner beginning of the selected label //$ The p element is appended to the inner beginning of the box tag
$("#box").prepend($p);
//This code is equivalent to prepend, but the caller has changed
//$p.prependTo($("#box")); - Add to the front of the selected label itself $ ("#box").before($p);
- Add after the selected label itself $ ("#box").after($p);
Delete DOM
Empty empty element
//Clear all the contents in the box element, and the box will remain. The return value is box $("#box").empty();
remove delete element
//Delete the box element, box disappears, and the return value is box //The remove d element is appended back to the page again, and its bound event will disappear $("#box").remove();
detach delete element
//Delete the box element, box disappears, and the return value is box //The element deleted by detach is appended back to the page again, and its binding time will follow $("#box").detach();
Differences between three deletion elements
- Empty will only empty the inside of the element, and remove and detach will clear the element together
- The event bound to the remove d element will disappear completely. When the element is appended to the page again, the event will not come back
- The event bound to the element deleted by detach will be retained. When the element is appended to the page again, the event will be bound automatically
Clone DOM
//Copy only box nodes let $box=$("#box").clone(); //Copy the box node and its bound events let $box2=$("#box").clone(true); //The copied node is appended to the page $("#main").append($box);
jQuery operation content
- Operation text content ()
- Operation tag content (HTML)
- Value of operation form element (VAL)
<body> <ul> <li><b>Option 1</b></li> <li><b>Option 2</b></li> <li><b>Option 3</b></li> </ul> <input type="text" value="Hello"> <input type="text" value="my bad"> <select> <option value="1">male</option> <option value="2" selected>female</option> </select> </body>
//The text function value will combine the text contents of all matched elements into one string let texts=$("li").text(); //Option 1 option 2 option 3 //The html function value only takes the internal content of the first matched element, including the tag structure let html=$("li").html(); //<b>Option 1</b> //The value of val function only takes the value of the first matched form element let val=$("input").val(); //Hello let sex=$("select").val(); //Gets the value of the value of the currently selected option $("li").text("Set text"); //All li tag text contents are changed to setting text, and the original b tag of li is overwritten $("li").html("<i>Set label</i>"); //All li label contents are italicized to set labels $("input").val("val Function settings"); //The value of the value attribute of all input tags is the set value $("select").val("1"); //Set the option with value 1 selected //Use the callback function to set the text content, and set the label and value attribute. The same is true $("li").text(function (index,text) { console.log(index);//Subscript of li console.log(text); //The original content of the current li tag //The callback function must give the return value, and the returned result is the final set value return index+1+text; });
- Summary: 1. The values of HTML function and val function only take the value of the first matched element, and text gets the value of all matched elements. 2. It is the same when setting online Unified settings are all override operations. 3.html functions can recognize html codes for formatting. 4.html and text functions are only valid for non form elements, and val is only valid for form elements. 5. Text or html function is used for button operation button text set by button tag. 6. Val is used for button operation button text set by input tag
jQuery operation size
Function name | describe | remarks |
height() | Gets / sets the height of the element | Set for parameter (numerical value, without unit, default px), otherwise get. |
width() | Gets / sets the width of the element | If you set the parameter, otherwise, you will get the width of the content, excluding the inner and outer margins and borders |
innerHeight() | Gets the height of the element | Height including inner margin |
innerWidth() | Gets the width of the element | Width including inner margin |
outerHeight() | Gets the height of the element | Contains the height of the inside margin and border |
outerWidth() | Gets the width of the element | Contains the width of the inner margin and border |
outerHeight(true) | Gets the height of the element | Contains the height of the outer margin, border, and inner margin |
outerWidth(true) | Gets the width of the element | Contains the width of the outer margin, border, and inner margin |
jQuery operation location
Function name | describe | remarks |
scrollTop() | Gets the height of the scroll bar | Generally, use $(window).scrollTop() to get the web page scroll bar |
scrollLeft() | Gets the distance the scroll bar scrolls to the right | Generally not used at present |
offset() | Gets the position of the element from the top of the document | The return values are as follows: {top:100,left:200} |
postion() | Gets the position of the positioned element from the positioned parent element. If all parents are not positioned, the vertex from the upper left corner of the browser content is returned | The return values are as follows: {top:200,left:100} |
- Get the scroll bar height. Use $(window).scrollTop() to get it. You should use html or body tags to set it
$("html,body").animate({scrollTo:0},1000);
jQuery event
Event registration and removal
- Event name function mode: only native events supported by HTML can be bound
- bind binding: the binding method of versions before 1.7 can also be used in the latest version, but it is not recommended.
- on binding: demonstration of event code binding in the recommended way after 1.7
//Function name binding $("#box").click(function(){ console.log("Function name binding"); }); //bind mode binding $("#box").bind("click",function(){ console.log("bind Mode binding"); }); //on mode binding $("#box").on("click",function(){ console.log("on Mode binding"); }); //on or bind bind multiple events at a time $("#box").on("click mouseover mouserout",function(){ console.log("Bind multiple events at a time"); });
Remove event code demo
//The unbind function removes an event $("#box").unbind("click"); //The off function removes the event $("#box").off("click"); //off or unbind to remove multiple events $("#box").off("click mouseout");
Active trigger event
//Trigger the click event of box through JS code $("#box").trigger("click");
Event object
The event object of jQuery must be used by passing parameters through the function triggered by the event. There is no compatibility problem
- Common event attributes are described as follows. screenX and screenY are based on the X-axis coordinates and Y-axis coordinates in the upper left corner of the screen. clientX and clientY are based on the X-axis coordinates and Y-axis coordinates in the upper left corner of the browser content. The scroll bars pageX and pageY are ignored. Based on the X-axis coordinates and Y-axis coordinates in the upper left corner of the page content, the scroll bar keyCode keyboard code stopPropagation() is calculated to prevent the event from bubbling preventDefault() Block default behavior return false; Prevent event bubbling and default behavior
jQuery animation
Built in animation
- Show and hide
- Slide down and slide up and slide Toggle
- Fadein and fadeout and fadetoggle
- Change to specified transparency: fadeTo
/* * The parameters of the built-in animation are as follows: * 1: number The number of milliseconds of type. By default, words of type 400/string represent normal, normal speed (400),fast(600),slow(200) * 2: function Type callback function, which represents the function to be executed automatically after the animation is executed * */ $("#show").click(function () { /*Control div display*/ $("#main").show("fast"); }); $("#hide").click(function () { /*Control div hiding*/ $("#main").hide("slow"); }); $("#sliderUp").click(function () { $("#main").slideUp(); }); $("#sliderDown").click(function () { $("#main").slideDown(); }); $("#toggleSlider").click(function () { $("#main").slideToggle(5000); }); $("#fadeIn").click(function () { $("#main").fadeIn(); }); $("#fadeOut").click(function () { $("#main").fadeOut(); }); $("#toggleFade").click(function (){ $("#main").fadeToggle(5000); }); $("#fadeTo").click(function () { /* * fadeTo The parameters are as follows: * 1.execution time * 2.The specified transparency. The optional values are 0-1. 0 means fully transparent and 1 means opaque * 3.Indicates the execution effect method. Optional values: swing indicates jog, which is the default value. Or linear means uniform velocity * 4.Callback function after animation execution * */ $("#main").fadeTo(3000,.4,"swing",function () { console.log("Transparency has been adjusted to 40%"); }); });
Custom animation
/* * animate The function parameters are as follows: * 1.Object type: set css attribute to perform animation [required] * 1.1: jQuery The transform attribute is not supported for animation * 2.Speed: the time required to execute the animation, in milliseconds [required] * 3.Execution effect: swing slow (default), linear constant * 4.Callback function: a function automatically called after the animation is executed * */ /* * jq The attribute name set in the animation shall conform to the setting of DOM object attribute name (hump naming) * For example: font size must be written as: fontSize * */ $("#d1").animate({left:"200px",opacity:".3",fontSize:"30px"},3000);
Queue animation
- Implementation of queue animation by callback function
- Chain programming to achieve queue animation (recommended)
$("#qu1").click(function () { /*Use the callback function to achieve the queue effect of animation*/ $("div").animate({left:"200px"},1500,"swing",function () { $("div").animate({opacity:0.4},1500,"swing",function () { $("div").animate({fontSize:"50px"},2000,"swing",function () { $("div").animate({top:"200px",height:"400px",width:"400px"},2000); }); }); }); }); $("#qu2").click(function () { /*Use chain programming to achieve the queue effect of animation*/ /* * delay The delay function is used to control the waiting time in milliseconds. The delay function can also be used in built-in animation * */ $("div").animate({left:"200px"},1500) .animate({opacity: 0.4},1500).delay(3000) .animate({fontSize: "50px"},1500) .animate({top:"200px",height:"400px",width: "400px"},2000); });
Wait for animation
Queue animation has been reflected
Stop Animation
Stop (whether to clear the queue and complete the current animation immediately);
$("#box").stop(true,true); / / clear the subsequent animation effect, and the current animation effect is completed immediately $("#box").stop(true,false); // When the subsequent animation effect is cleared, the current animation effect stops immediately, and the second parameter can be omitted $("#box").stop(false,true); / / the subsequent animation will continue to execute, and the current animation will be completed immediately $("#box").stop(false,false); // The subsequent animation will continue to execute, and the current animation will stop immediately. The effect can omit two parameters
jQuery plug-in
Common plug-ins
- [jQueryUI] https://jqueryui.com/
- [bootstrap] https://www.bootcss.com/
- [easyUI] https://www.jeasyui.net/
- [layui] https://www.layui.com/
- [jQuery plug-in library] https://www.jq22.com/
Custom plug-ins
- Static method setting static method: $. Method name = function ([parameter list]); Use static methods: $. Method name ([argument list]); (function($){
//Gets a random number in the specified range
$.getRandom=function (min,max) {
if(min>max){
let temp=max;
max=min;
min=temp;
} if(min==max){
return min;
}else{
let r=Math.floor(Math.random()*(max-min+1)+min);
return r;
} } })(jQuery);
console.log($.getRandom(5,25)); - Instance method setting instance method: $. fn. Method name = function([parameter list]); using instance method: $(selector). Method name ([argument list]);
(function($){ //Set the color attribute of an element $.fn.changeColor=function (color) { this.css("color",color?color:"red"); } })(jQuery); //If no parameters are passed, set the font color of box to red $("#box").changeColor(); //If you pass the correct parameters, set the font color of box to the specified color $("box").changeColor("#FFF "); / / set the font color of box to white
jQuery classic case
Seamless rotation
- Page code
<div class="main"> <div class="banner-list"> <div class="banner-item"><a href=""><img src="images/ad-1.png" alt=""></a></div> <div class="banner-item"><a href=""><img src="images/ad-2.png" alt=""></a></div> <div class="banner-item"><a href=""><img src="images/ad-3.png" alt=""></a></div> </div> <div class="banner-opt"> <span class="left"><</span> <span class="right">></span> <ul> <li class="active"></li> <li></li> <li></li> </ul> </div> </div>
- Style code
*{ padding: 0; margin: 0; } .main{ height: 300px; width: 380px; position: relative; margin: 100px auto; overflow: hidden; } .banner-list{ position: absolute; left: 0; top: 0; } .banner-list div{ float: left; } .banner-opt span{ display: none; height: 20px; line-height: 20px; width: 20px; text-align: center; background-color: #ccc; color: #fff; position: absolute; top: 50%; margin-top: -10px; cursor: pointer; } .banner-opt span.left{ left: 0; } .banner-opt span.right{ right: 0; } .main:hover .banner-opt span{ display: block; } .banner-opt ul{ list-style: none; width: 45px; height: 25px; position: absolute; left: 50%; margin-left: -22px; bottom: 5px; display: flex; align-items: center; justify-content: space-between; } .banner-opt ul li{ height: 10px; width: 10px; background-color: #ccc; border-radius: 50%; } .banner-opt ul li.active{ background-color: #5cb85c; border: 2px solid #fff; }
- Effect code
/*Initialize the rotation chart. The subscript is selected by default*/ let index=0; /*Initialization timer*/ let inter; $(function(){ /*Seamless rotation*/ /*1.Copy first item*/ let $itemFirst=$(".banner-item").eq(0).clone(true); /*2.Append to end*/ $(".banner-list").append($itemFirst); /*3.Update the width of the rotation box: the width of the banner item * the number of banner items*/ let listWidth=$(".banner-item").length*$(".banner-item").width(); $(".banner-list").width(listWidth); /*Next button*/ $(".right").click(next); /*Previous button*/ $(".left").click(prev); /*When the mouse enters, the rotation will be stopped, and when the mouse moves out, the rotation will continue*/ $(".banner-list").mouseover(stopMove).mouseout(autoMove); /*Page loading will automatically rotate*/ autoMove(); }); /*Switch to next*/ function next() { index++; if(index===$(".banner-item").length){ index=1; $(".banner-list").css("left",0); } moveItem(index); } /*Switch to previous*/ function prev(){ index--; if(index===-1){ index=$(".banner-item").length-2; $(".banner-list").css("left",($(".banner-item").length-1)*$(".banner-item").width()*-1); } moveItem(index); } /*Mobile carousel map*/ function moveItem(i) { $(".banner-list").stop().animate({"left":-i*$(".banner-item").width()},500); /*Rotation indication point setting*/ if(i==$(".banner-item").length-1){ $("li").eq(0).addClass("active").siblings().removeClass("active"); }else{ $("li").eq(i).addClass("active").siblings().removeClass("active"); } } /*Automatic rotation*/ function autoMove() { inter=setInterval(next,1500); } /*Stop automatic rotation*/ function stopMove() { clearInterval(inter); }