当前位置:网站首页>html

html

2020-11-06 01:16:15 one who tries not to offend anybody

unit01-HTML、CSS

HTML: A technique for developing web pages

CSS: Used to modify 、 A technique for rendering web pages

HTML+CSS Can develop a very beautiful one 、 Very beautiful web page

Develop web pages Build a house

HTML Tags build the structure of a web page brick ( Building the structure of the house )

CSS attribute lime 、 Paint, etc

HTML summary

HTML What is it?

HTML(Hyper Text Markup Language): Hypertext markup language

Hypertext : Hypertext 、 Beyond the text ( It can contain data other than text , For example, pictures 、 Audio 、 Video and other formats )

Mark : It's also called a label 、 Elements 、 Nodes etc. , It's using angle brackets (<>) It's a set of things to wrap up , for example :

<head> <body> <div> <span> <table> etc. 

HTML Is the most basic language for developing web pages .

HTML from W3C Provided by organization (CSS/xml)

About HTML The details of the :

(1) Use HTML Web pages are usually developed with .htm or .html For the suffix !

(2) Use HTML The developed web page file is parsed and displayed by the browser ( The browser is a html Parser )

(3)HTML It's a kind of document (txt/word/ppt/pdf etc. )

summary : HTML It's a language for developing web pages !!

HTML Structure

1、 Case study : Write my first HTML Webpage , And open it with a browser

Create a new one txt file , Change the suffix to .html, The code implementation is as follows :

<!DOCTYPE html>
<html>
    <head>
        <title> The title of the page </title>
    </head>
    <body>
        <h1>Hello CGB2003...</h1>
    </body>        
</html>

2、HTML The structure,

(1)<!DOCTYPE HTML>  The document statement ,  Used to declare HTML The document follows HTML Specification and version 
     It's on it html5.0 Statement of ,  It's also the most commonly used version 
(2)<html></html>  Root tag ,  Used to wrap all web content ( Except for the document statement )
(2)<head></head>  The first part ,  For storage HTML Basic attribute information of the document ,  For example, the title of a web page ,  The code used by the document, etc ,  This information will be loaded by the browser first .
(3)<body></body>  The body part ,  Used to store visual web content .  That's real Web Data 
(4)<title></title>  Declare the title of the page 
(5)<meta charset="utf-8" >  Used to inform the browser which code to use to open HTML file ,  This code must be consistent with the code when the file is saved ,  There will be no Chinese garbled problem .

HTML grammar ( understand )

1、html label

label : It's also called a marker 、 Elements, etc. , Tags are divided into start tags , for example :

<head>、<body>

And the end tag , for example :

</head>、</body>

There can be other content between the start tag and the end tag .

<head>
    <titile> Declare the title of the page </title>
    <meta charset="utf-8">
</head>

Some tags have nothing to wrap between the start tag and the end tag , Usually it can be written as a self closing label , for example :

<br/> <hr/> <input/> <img/> <link/> etc. 

2、html attribute

You can declare properties on tags ( Attributes cannot exist on their own , Must be declared on the label )

<div id="d1" class="c1" style="color:red;"> This is a div Elements </div>

Multiple attributes can be declared on the tag , Multiple attributes are separated by spaces

The values of attributes on tags can be enclosed in single or double quotation marks

<meta charset="UTF-8" id="m1">
<meta charset='UTF-8' id='m1'>

3、html notes

Format : <!-- The comment -->

The function of annotation : (1) Add an explanation to the code

(2) Comment on some code that you don't need to execute for the time being

Browser for html The content in the comment will not parse , It doesn't show !

4、html Spaces and line breaks

In the browser , Multiple consecutive white space characters ( Space 、 tabs tab、 Line break ) Will be displayed as a space by the browser . that :

How to make a new line in a web page : have access to <br/> Tag line breaks

How to make a space in a web page : have access to &nbsp; or &emsp; Make a space

Add : HTML Is case insensitive !

HTML Chinese grammar is very lax !( For example, case mixing , Or the label has only the beginning and no end , Or unreasonable nesting of tags ), But we're writing HTML Write according to the specification .

HTML label

Image tag

adopt img Tags can insert an image into a web page

<!-- 
     It is not recommended to write an absolute path with a drive letter , Because the project will be released in the future , The position will change , Then we have to change the path of the picture 
<img src="D:/JavaDevelop/WS_CGB2003_WEB/day05-htmlcss/WebContent/img/meinv.jpg"/>
 -->
<!-- 
    ./:  Represents the current directory ( The directory where the current file is located ), Due to the current html stay WebContent Under the table of contents 
     therefore  ./ Call means WebContent Catalog ,  in addition  ./  It can be omitted !
    ../:  Indicates that the current directory is one level above the current directory ( This is the parent directory of the current directory )
    ../../:  Represents the level above the current directory ( That is, the parent directory of the parent directory of the current directory )
 -->
<img src="./img/meinv.jpg" width="50%"/>
<img src="./img/lpx.jpg"  width="50%"/>

among src Property is used to specify the path of the image ( The path of the picture should not be an absolute path with a drive letter , Relative path is recommended )

width Property is used to specify the width of the picture

height Property is used to specify the height of the image

Hyperlink label

Hyperlinks are a label , adopt a Tags can create a hyperlink to another document in a web page

Click the hyperlink to jump to another page ( picture / Download path, etc ), Example :

<!--  Jump to a local web page  -->
<a href="01- First page .html">01- First page .html</a>
<!--  Jump to Baidu home page  -->
<a href="http://www.baidu.com"> use Baidu Search , You don't know </a>
<br/>
<!--  Click on the picture to jump to tmooc -->
<a target="_blank" href="http://www.tmooc.cn">
    <img alt="tmooc" src="imgs/tmooc.png" />
</a>

among href Property is used to specify which link to jump to after clicking the hyperlink URL Address

target Property is used to specify how to open the hyperlink

_self: The default value is , Means to open a hyperlink in the current window

_blank: Indicates that hyperlinks are opened in a new window

Tabular label

1. Case study : Insert a 3*3 Table for

<h1> Case study : Insert a 3*3 Table for </h1>
<table><!--  Used to define a table in a web page  -->
    <tr><!--  Used to define a table row  -->
        <th> Header 1</th>
        <th> Header 2</th>
        <th> Header 3</th>
    </tr>
    <tr>
        <td>11</td><!--  Used to define a cell  -->
        <td>12</td>
        <td>13</td>
    </tr>
    <tr>
        <td>21</td>
        <td>22</td>
        <td>23</td>
    </tr>
    <tr>
        <td>31</td>
        <td>32</td>
        <td>33</td>
    </tr>
</table>

The display effect in the browser is as follows :

stay head Add the following to the tag :

<style>
    /* style Only... Can be written in the label css Annotation and css Code  */
    table{
        border:*2px solid red; /*  Add a border to the table  */
        border-collapse: collapse; /*  Set border merge  */
        background-color: pink; /*  Set the background color for the table  */
        width: 70%; /*  Set the width for the table  */
        /* margin-left: 15%; */
        /*  Set the table's left margin and right margin adaption ( Make sure the two are always equal ) */
        margin-left: auto;
        margin-right: auto;
    }
    td,th{
        border:2px solid red; /*  Add borders to cells  */
        border-collapse: *collapse*; /*  Set border merge  */
        padding: 5px; /*  Set the distance between the cell border and the content ( padding ) */
    }
    h1{
        /* border: 2px solid blue; */
        text-align: *center*; /*  Set the content in the element to center horizontally  */
    }
</style>

Refresh the browser again, the display effect is :

2、 Table label Introduction

table --  Used to define a table in a web page 
tr --  Used to define rows in a table 
td --  Used to define cells in a table 
th --  Used to define the cells in the header row (th The text in is centered by default , And make it bold )

3、 practice : Use table tags to create a table in a web page , Here's the picture :

Requirements are as follows :

(1)  The contents of the table are as follows ,  And set the table border 
(2)  Set no gaps between cells ,  And set the distance between cell border and content to 5px
(3)  Set the background color of the table to pink,  And set the width of the table to 70%
(4)  Set the table to center in the web page ,  And add a header and a title to the table 

Form labels

1、 What forms do : Used to submit data to the server

There are two ways to submit data to the server :

(1) Submit data to the server through a form

Forms can contain form item tags , You can fill in data in the form item ( For example, user name 、 Password etc. ), Fill in and submit the form , The data in the form can be submitted to the corresponding server .

(2) Submit data to the server via hyperlinks

http://www.baidu.com?username= Zhang San &pwd=123&like= Basketball 

<a href="http://www.baidu.com?username= Zhang San &pwd=123&like= Basketball " target="_blank"> use Baidu Search , You don't know !</a>

In the address bar URL The address is followed by a question mark (?) You can splice parameters , Parameters can have multiple , Use... Between multiple parameters & Separate , Parameters are also divided into parameter names ( for example :username/pwd/like) And parameter values ( for example : Zhang San /123/ Basketball ), At the same time of accessing Baidu server after carriage return , You can take the parameters stitched after the question mark to Baidu server .

2、 Form labels

<form action="url Address " method=" submission "></form>

among action Property is used for Specify the submission address of the form , for example , take action Point to Baidu server , It means that when you fill out the form in the future , Submitting the form will submit the data in the form to Baidu server .

method="GET/POST" Attributes are used for Specify how the form should be submitted , The common one is GET and POST Submit .

Form item labels

1、input Elements :

(1) Normal text input box ( such as : user name / nickname / mailbox / Verification code, etc )

<input type="text" name="username"/>

(2) Password input box ( such as : password / Confirm password, etc )

<input type="password" name="pwd"/>

(3) Radio buttons ( such as : Gender / Department, etc )

<input type="radio" name="gender"/> male 

(4) Check box / Checkbox ( such as : hobby / Post, etc )

<input type="checkbox" name="like"/>

(5) General button ( such as : Change a picture )

<input type="button" value=" In a "/>

The normal button itself has no function , But we can pass js Add function or behavior to a button

(6) Submit button ( such as : Submit / register / Sign in )

<input type="submit" value=" Submit / register / Sign in "/>

The submit button is used to submit the data in the form to the server !

2、select、option label :

<select name="city">
    <option value="beijing"> Beijing </option>
    <option value="shanghai"> Shanghai </option>
    <option selected="selected"> Guangzhou </option>
    <option> Shenzhen </option>
</select>

select Used to define a drop-down box

option Used to define the options on the drop-down box

selected Set up current option Options are selected by default

3、textarea Multi line text input area :

<textarea name="description" cols="30" rows="5"
placeholder=" Please enter the description information ..."></textarea>

cols attribute : Used to set the number of columns in the text input box ( Width )

rows attribute : Used to set the number of lines in the text input box ( Height )

placeholder attribute : Set the prompt message in the input box !

Form details

1、 When you submit the form , Why is the data in the form not submitted ?

For form item tags in a form , As long as you need to submit data to the server , The form item must be added with name attribute ; If the form item label doesn't have name attribute , When the form is submitted , This item will be ignored . for example :

<input type="text" name="username"/>
<input type="password" name="psw"/>

2、 How to make multiple radio boxes only have one selected ?

Multiple radio boxes must have the same name Property value , If there are multiple radio boxes name Same property value , It means the content of a group , Only one of the radio boxes in a group can be selected !

<td> Gender :</td>
<td>
    <input type="radio" name="gender"/> male 
    <input type="radio" name="gender"/> Woman 
</td>

3、 Radio box why 、 The values submitted after selecting an item in the check box are on?

Because the radio box 、 The check box can only select , Different from the user name 、 Password input box , You can enter content .

So we need to pass value Property to set the submitted value for the radio box or check box ( If you don't set the default values are on), for example :

<input type="radio" name="gender" value="male"/> male 
<input type="radio" name="gender" value="female"/> Woman 

4、 How to set a radio box or check box to select an item by default ?

You can add a checked="checked" attribute , You can make the current radio box or check box selected by default . for example :

<input type="radio" checked="checked" name="gender" value="male"/> male 
<input type="radio" name="gender" value="female"/> Woman 
<!--  Hobbies check box / Checkbox  -->
<input type="checkbox" name="like" value="basketball"/> Basketball 
<input type="checkbox" checked="checked" name="like" value="football"/> football 
<input type="checkbox" name="like" value="volleyball"/> Volleyball 

5、 How to set the drop-down box to select an item by default ?

stay option Add a... To the label selected="selected" attribute , Can make the present option Options are selected by default , example :

<select name="city">
    <option> Beijing </option>
    <option> Shanghai </option>
    <option selected="selected"> Guangzhou </option>
    <option> Shenzhen </option>
</select>

6、 Drop down the box option Options value What is the function of attributes ?

<select name="city">
    <option value="beijing"> Beijing </option>
    <option value="shanghai"> Shanghai </option>
    <option selected="selected"> Guangzhou </option>
    <option> Shenzhen </option>
</select>

If an option is selected , And add... To this option value attribute , When you submit the form , Will be submitted value The value of the property .

If an option is selected , There is no add on this option value attribute , When you submit the form , The content of the tag will be submitted

Other labels

stay html5 Before , Most of the audio and video is through plug-ins ( such as flash) To play ,html5 Provides for the passage of audio and video Element to contain audio and video standard methods .

1、audio label (html5)

audio Tags can play sound files or audio streams , for example :

<audio controls src="audio/ Desert camel _ Exhibition and Rollo .mp3"></audio>

among audio Attributes of the tag :

src attribute : Used to specify the audio to be played URL Address 
controls="controls": Display playback controls for users , For example, play 、 Pause and volume control, etc 
autoplay="autoplay": The audio will play as soon as it is ready ( Auto play )
loop="loop": When the audio is finished playing , Start playing again ( Loop Playback )
width、height: Set the width and height of the audio player 

<audio> And </audio> The content inserted between is not supported by audio Element's browser shows

<audio controls src="audio/ Desert camel _ Exhibition and Rollo .mp3">
     If you can see this , Indicates that your browser does not support this tag !
</audio>

2、video label (html5)

video Tags can play video streams , Three video formats are currently supported :MPEG4、Ogg、WebM.

<video controls src="video/ Xiaofang _ Li Ronghao .mp4"  width="50%"></video>

among video Attributes of the tag :

src attribute : Used to specify the video to be played URL Address 
controls="controls": Display playback controls for users , For example, play 、 Pause and volume control, etc 
autoplay="autoplay": The video plays as soon as it's ready ( Auto play )
loop="loop": When the video is finished playing , Start playing again ( Loop Playback )
width、height: Set the width and height of the video player 

<video> And </video> The content inserted between is not supported by audio Element's browser shows ( Here are no examples )

3、div、span、p label

div、span、p The elements are very common 、 But it's a very common label , They're all container labels , Can be used to wrap other elements or text , Add styles to these elements , You can style the content that is included in it .

div、p: A block element , Default exclusive line , Width and height can be set ( among div Elements are usually used for layout , and p Elements are usually used to define paragraphs )

span: Inline elements , In line elements can be displayed on the same line , Width and height cannot be set (span Used to contain text or combine inline elements , In order to facilitate the uniform setting of styles )

4、header、footer label (html5)

<header> The tag defines the header of the document ( Introducing information ) Or the header of the page

<footer> Tags define the footers of a document or section . The footers usually contain the author of the document 、 Copyright information 、 Terms of use link 、 Contact information, etc .

Registration form case

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
/* style Only... Can be written in the label css Annotation and css Code  */
table {
    border: 2px solid red; /*  Add a border to the table  */
    border-collapse: collapse; /*  Set border merge  */
    background-color: lightgrey; /*  Set the background color for the table  */
    /* margin-left: 15%; */
    /*  Set the table's left margin and right margin adaption ( Make sure the two are always equal ) */
    margin-left: auto;
    margin-right: auto;
}

td, th {
    border: 2px solid red; /*  Add borders to cells  */
    border-collapse: collapse; /*  Set border merge  */
    padding: 5px; /*  Set the distance between the cell border and the content ( padding ) */
}

h1 {
    /* border: 2px solid blue; */
    text-align: center; /*  Set the content in the element to center horizontally  */
}
</style>
</head>
<body>
    <h1> Welcome to register </h1>
    <form action="#">
        <table>
            <tr>
                <!--  User name input box  -->
                <td> user name :</td>
                <td><input type="text" name="username" /></td>
            </tr>
            <tr>
                <!--  Password input box  -->
                <td> password :</td>
                <td><input type="password" name="pwd" /></td>
            </tr>
            <tr>
                <!--  Gender radio box  -->
                <td> Gender :</td>
                <td><input type="radio" checked="checked" name="gender"
                    value="male" /> male  <input type="radio" name="gender" value="female" /> Woman 
                </td>
            </tr>
            <tr>
                <!--  Hobbies check box / Checkbox  -->
                <td> hobby :</td>
                <td><input type="checkbox" name="like" value="basketball" /> Basketball 
                    <input type="checkbox" checked="checked" name="like"
                    value="football" /> football  <input type="checkbox" name="like"
                    value="volleyball" /> Volleyball </td>
            </tr>
            <tr>
                <!--  City drop-down box  -->
                <td> City :</td>
                <td><select name="city">
                        <option value="beijing"> Beijing </option>
                        <option value="shanghai"> Shanghai </option>
                        <option selected="selected"> Guangzhou </option>
                        <option> Shenzhen </option>
                </select></td>
            </tr>
            <tr>
                <!--  Self description   Multiline text input box  -->
                <td> Self description :</td>
                <td><textarea name="description" cols="30" rows="5"
                        placeholder=" Please enter the description information ..."></textarea></td>
            </tr>
            <tr>
                <!--  Submit button  -->
                <!-- colspan:  Set the number of columns the cell spans  -->
                <td colspan="2" style="text-align: center;"><input
                    type="submit" value=" Submit " /></td>
            </tr>
        </table>
    </form>
</body>
</html>

CSS summary

What is? CSS?( understand )

CSS: Cascading style sheets , Used to modify 、 A technique for rendering web pages

Use css Style embellishes the web page , You can implement css Code and display data html Code separation , Enhance the display ability of the web page !

stay HTML Introduction in CSS

The way 1: adopt style Attribute introduction css( Not recommended )

<!-- 
    1. By... On the label style Attribute to div Set the style  
     Frame :2px solid red 
     font size :26px
     The background color is :pink
-->
<div style="border:2px solid red;font-size:26px; background:pink;"> This is a div...</div>

Because the above way is to css Style code , Written directly on the label style Attribute internal , If there are too many attributes , Easy to cause page structure confusion , Not conducive to later maintenance .

Write the style code on the label , The style code only works for the current tag , Code can't be reused !

And in this way, you can't make html Labels and css Style separation !

This is not recommended !( Such passage style Attribute added style , It's called in line styles / inline style )

The way 2: adopt style Tags introduced css

stay head You can add a style label , stay style The inside of the label can be written directly css style

In this way, all of the css Style code is concentrated in a style Internal unified management of labels , This method will not cause confusion of page structure , And you can reuse the code !

The initial realization will be html Tag code and css The style code is separated !

Code example :

<!-- 2. adopt style Label to span Set the style as follows : 
     Frame : 2px solid green
     font size : 30px
     Bold font 
-->
<head>
<meta charset="utf-8">
<style type="text/css">
    /* ****** CSS style  ****** */
    span{ /*  For the current html All in span Label setting style  */
        border:2px solid green;
        font-size:30px;
        font-weight:bolder; /* bold/bolder */
    }
</style>
</head>

The way 3: adopt link Links introduce external css file

stay head The label inside , Through one link Tags can introduce external CSS file

In this way, all of the css The code is concentrated in a single css Unified management in documents , The real realization will be css Code and html Code separation , Realize the reuse of code .

Code example :html Introduction in demo.css file

<!-- 3. adopt link The label introduces the external css file , by p The element settings are as follows : 
     Frame : 2px solid blue;
     The font color :red
     The font is set to Chinese amber 
     Set the first line of text indentation 50px
-->
<!--  introduce demo.css file ( Style in ) -->
<link rel="stylesheet"  href="demo.css"  />

demo.css file

@charset "UTF-8";
p{
    border: 2px solid blue;
    color: red;
    font-family: " Amber in Chinese ";
    text-indent: 50px;
}

CSS Selectors

The so-called selector is able to be in html A technique that helps us select elements for decoration .

Tag name selector

By element name ( Or tag name ) Select all tags with the specified name

Format : Element name / Tag name { css style ... }

/* ----- 1. Label name selector exercise  ----- 
 Will all span The background color of the label is set to #efbdef,  Set the font size to 22px, Bold font ;*/
span{ /*  Check all span Elements  */
    background-color:#efbdef; 
    font-size: 22px;
    font-weight: bolder;
}

class Selectors

You can add a generic attribute to the element -- class, adopt class Set the attribute of the element to which it belongs ,class Elements with the same value are a group of . adopt class Value can select the elements of this group , Add styles to elements .

Format :.class value { css style ... }

example :

/* ----- 2. Class selector exercise  ----- 
(1) Will all span( But not including div and p Label under span) The background color of is set to #faf77b, Border changed to 2px solid cyan;
(2) take div Under the span And the contents are "span111" Of span, The background color is set to #5eff1e、 Font color settings 
#ec0e7e;*/
.s1{ /*  Select all class The value is s1 The elements of  */
    background: #faf77b;
    border: 2px solid cyan;
}
.s2{ /*  Select all class The value is s2 The elements of  */
    background: #5eff1e;
    color: #ec0e7e;
}

in addition , An element can also be set to more than one class value , Multiple class Values are separated by spaces , for example :

<span class="s1 s2" >span111</span>

Indicates that the current element belongs to multiple groups at the same time , Styles set on multiple groups also work on the current element .

If multiple groups have the same style ( But the value is different ), Styles conflict , The style written after will override the previous style !


Content supplement : Selector priority order :

(1) If it's the same kind of selector , At the same time, some elements are styled , If styles conflict , Then the style written in the back will cover the previous style .

(2) If it's a different selector , Set the style priority order as follows :id Selectors (100) > Class selectors (10) > Element name selector (1)


id Selectors

Through the common attributes on the tag id, You can set a unique number for the label (id The value should be unique ), adopt id Value can uniquely select an element .

Format :#id value { css style }

/* ----- 3.id Selector practice  -----
 use id The selector will be the first p Label set font size to 24px, The font color is #a06649,  Indent the first line of text 20px.*/
#p1{ /*  Choose id The value is p1 The elements of  */
    font-size:24px;
    color: #a06649;
    text-indent: 20px;
}
<p id="p1"> This is a p Elements !!!</p>

Descendant selector

Select the specified descendant element inside the specified element

Format : The ancestors Progeny { css style ... }

/* ----- 4. Progeny selector exercise  ----- 
 by p Everything inside the element span Elements , Set the font size to 18px, The font color is red , The background color is pink;*/
p span{ /*  Match all p Everything inside the element span Elements  */
    font-size:18px;
    color: red;
    background: pink;
}
/* p,span{}  Match all p Elements and all span Elements  */
<p id="p1">
     This is a p Elements !!!
    <span> This is a span Elements !!!</span>
</p>

Attribute selector

Based on the element selected by the selector , Filter according to the attribute conditions of elements / Filter element

Format : Selectors [ Property conditions 1][ Property conditions 2]...{ css style }

/* ----- 5. Attribute selector  ----- 
 For all text input boxes , Set the background color to #FF7CCC、 font size 22px, Indent the first line of text 15px;*/
input[type='text']{ /*  Match all input also type The value is text The elements of  */
    background: #FF7CCC;
    font-size: 22px;
    text-indent: 15px;
}
input[type='text'][name='email']{ 
    /*  Check all input also type The value is text、 also name by email The elements of  */
    background : yellow;
}

Summary of common attributes

Text attribute

1、text-align: Set the horizontal alignment of text within the element , Its common value is :

left:  The default value is . Align left 
right:  Right alignment 
center:  Align center 
justify:  full-justified 

2、text-decoration: Set the underline style of the text , Its common value is :

underline:  Underlined 
none:  No underline 

3、text-indent: Set the first line of text to indent , Company : Pixels / percentage

4、letter-spacing: Set character spacing / spacing , Its common value is :

normal
 Pixel values 

5、text-shadow: Set font shadow , Its value is :

 Pixel values   Pixel values   Pixel values   Color value 
 The first value is the shadow horizontal shift , The second value is the shadow vertical shift , The third value is the shadow spread value , The fourth value is the shadow color 

Font properties

font-size: Set font size

font-weight: Set font thickness normal、bold、bolder 100/200/300../900

font-family: Set the font , For example, Microsoft YaHei 、 In black 、 Regular script, etc

color: Set font color

Background properties

background-color: Set the background color

background-image: Set the background image ,url(' Path to picture ');

background-repeat: Set or retrieve whether and how the background image of the object is arranged , Common values :

repeat( The default value is , To arrange repeatedly )
repeat-x( Repeat horizontally , But not vertically )
repaet-y( Repeat it vertically , But not horizontally )
no-repeat( No repetition )

background-position: Set or retrieve the background image position of the object

background: The background color Background image Whether the background image is repeated The location of the background image

Frame (border)

border:2px solid red; -- Set the border of the element ( You can also set the width of the border 、 style 、 Color )

border Properties can be split into the following settings :

border-width: 2px; --  Set the width of the element border 
border-style: solid; --  Set the style of the element border 
border-color: red; --  Set the color of the element border 

among border-width、border-style、border-color It can also be split according to the upper right lower left direction , With border-width For example :

border-top-width: 2px; --  Set the width of the upper border 
border-left-width: 2px; --  Set the width of the left border 
border-right-width: 2px; --  Set the width of the right border 
border-bottom-width: 2px; --  Set the width of the lower border 

Other attributes

width: Set the width of the element

height: Set the height of the element

margin: Set the outer margin of the element

margin-top: 10px; --  Set the top and outer margins of the element to 10px;
margin-right: 20px; --  Set the outer right margin of the element to 20px;
margin-bottom: 30px; --  Set the bottom margin of the element to 30px;
margin-left: 40px; --  Set the left margin of the element to be 40px;
---------------------------------------------
margin: 10px 20px 30px 40px; --  On   Right   Next   Left ,  Clockwise corresponds to 
margin: 10px 20px 30px; --  On   about   Next 
margin: 10px 20px; --  Up and down   about 
margin: 10px; --  Up, down, left and right 10px;

Add : color setting

There are three common ways of color selection :

Mode one : Set color name , for example :

red、green、blue、yellow、cyan、pink、white、black etc. 

Mode two : Set up # Add six hexadecimal numbers

#FF0000(red)、#00FF00(green)、#0000FF(blue)、#FFFF00(yellow)、#00FFFF(cyan) etc. 

Mode three : Set up rgb Color value ( break :14:46-15:06 )

rgb(255,0,0) 、rgb(0,255,0) 、rgb(0,0,255) 、rgb(255,255,0) 、rgb(0,255,255)  etc. 
(red) (green) (blue) (yellow) (cyan)

Web development practice

complete JT The landing page in the project !

complete JT Registration page in project !( Selected as !)

Registration page video :https://www.bilibili.com/vide...

Extended content

display attribute

display Used to set the type of the element , Common values :

block: Default values for block level elements 
     By default, one row is exclusive 
     Width and height can be set 
inline: Default values for inline elements 
     By default, multiple in line elements can be on the same line 
     Generally, width and height cannot be set 
inline-block: Inline block element 
     Multiple elements can be displayed on the same line ,  You can also set the width and height 
none: Represents hidden elements 

Element type ( understand )

div/span/p They are all container labels , For wrapping other content ( These elements themselves don't have much style !)

p: Block-level elements , Default exclusive line , Used to wrap a piece of text ( Use for writing articles p Label each piece of content )

div: Block-level elements , Default exclusive line , For wrapping other content , Set the style to div On , Can act on div On the content of .

span: Inline elements , By default, it can be displayed on the same line as other elements .

(1) Block-level elements (block)

By default , Block level elements have one row exclusive

You can set the width and height , If it is set, the width and height are set

If you don't set the width and height , Where width is the default fill parent element , And the height is determined by the content ( Supported by content )

such as : div/p/h1~h6/form/table And so on are block level elements

(2) Inline elements (inline)

By default , Multiple in line elements can be on the same line

Cannot set width and height

such as : span/input/img/i/b And so on are in line elements

(3) Inline block element (inline-block)

It has the characteristics of in line elements ( Can be displayed in the same row ), It also has the characteristics of block level elements ( You can set the width and height )

unit02-JavaScript

JavaScript brief introduction

What is? JavaScript( understand )

The full name is JavaScript, It's called JS

from NetScape( netscape ) The company offers , It's a scripting language specifically embedded in browsers

LiveScript JavaScript

JS Run in browser , Responsible for the animation effect in the web page

Or to achieve form verification and other functions

JS Features and advantages ( understand )

1、 characteristic :

(1)JS It's a literal language ( Explain and execute , There is no compilation process )

java--> At the time of writing xx.java ---> Translate it into xx.class --> function class file

js ---> At the time of writing html, At the time of writing js file , Direct operation , No compilation process

(2)JS It's an object-based language (JS There is no concept of a class in , There is no compilation process )

JS There are objects in ( Built-in objects 、 Custom object )

(3)JS It's a weak type of language (Java: Strong type )

// stay java in :  Once a variable is declared ,  It's a fixed data type ,  Can't be changed 
String str = "abc";
int number = 100;
// stay JS in :  Variables are type insensitive ,  Can point to any data type 
var s = 100; //number( value type )
s = "abc";    //string( String type )
s = true; //boolean( Boolean type )
s = []; //object( object type )
s = function(){} //function( object type ) 

2、 advantage :

(1)JS It has good interactivity

(2)JS With a certain degree of security ( Can only run inside the browser , Can't access resources outside the browser )

(3)JS Cross platform (JS browser )

( JS Language is cross platform , It's because there's a browser , But browsers don't cross platform

Java Language is cross platform , Because there are virtual machines , But virtual hosts don't cross platform )

stay HTML Writing JS The way

1、 stay script The inside of the label can be written JS Code :

stay head perhaps body You can add a script label , stay script The inside of the label can be written directly JS Code !

<!--  stay script The inside of the label can be written JS Annotation and JS Code  -->
<script type="text/javascript">
    //JS Single line comment for 
    /* JS Multiline comments for  */
    alert( " stay html Introduction in JS The first way ..." );
</script>

2、 adopt script The label introduces the external JS file

stay head or body The label inside , Can pass script The label introduces the external JS file . for example :

<!--  adopt script Tags can introduce external JS file  -->
<script src="demo.js"></script>

Be careful :(1) In the introduction of js Of documents script Don't write inside the label JS Code , for example :

<script src="demo.js">
    alert( 111 ); // The code here doesn't execute 
</script>

(2) Don't introduce JS Of documents script Label self closing , Because it may lead to file import failure , as follows :

<script src="demo.js" />

Extended content : You can also write directly on the elements JS Code

<!--  Write directly on the element JS Code :
onclick Attribute is used to bind a click event to the current element : Clicking on an element triggers an event , Execute the corresponding function 
-->
<input type="button" value=" Am I ~" onclick="alert(' You dare to order it !!!')"/>
<input type="button" value=" Don't order me "  onclick="console.log( new Date() )"/>

JavaScript grammar

Annotation format

JS Note symbols and Java The annotation symbol of is the same as , as follows :

//  Single line comment content 
/*  Multiline comment content  */

data type

1、 Basic data type

(1) value type (number)

stay JS in , All values are floating-point at the bottom , But in the process of processing and display, it will automatically convert to integer .

 for example :2.4+3.6=6
 Special values :Infinity( infinity ) / -Infinity( Negative infinity ) / NaN( The digital )

(2) String type (string)

stay JS in , The string type belongs to the basic data type , String constants can be enclosed in single or double quotation marks . for example :

var s1 = "Hello JS";
var s2 = 'Hello JS';

in addition ,JS There are corresponding wrapper objects for string types in (String), It will automatically convert to the wrapper object when needed .

var s1 = "Hello JS"; // Basic data type , string
console.log( typeof s1 ); //string
var s2 = new String("Hello JS"); // Complex data type , object
console.log( typeof s2 ); //object
// Regardless of the basic data type s1,  Or object type s2,  Can be used as an object 
console.log( s1.valueOf() ); //s1 It's the basic data type ,  It turns into an object ,  call valueOf function 
console.log( s2.valueOf() );

(3) Boolean type (boolean)

There are two Boolean values , Respectively true and false.

(4)undefined type

undefined There is only one value of type , Namely undefined, Indicates that the variable is undefined ( But it's not that variables are not declared ).

A variable is declared , But there is no assignment to the variable , The value of the variable is undefined.

/* 1.undefined type  */
var x;
alert( x ); //undefined
alert( y ); // Throw exceptions 

(5)null type

null There is only one value of type , Namely null, Indicates null value .

Can be the return value of a function , Indicates that the function returns an empty object .

Be careful :null and undefined Variables of type cannot call functions or properties , Would throw exceptions !

2、 Complex data type

Mainly refers to the object (JS Built in objects for 、 Custom objects 、 function 、 Array )

Variable declarations

JS China is through var Keyword declaration variables , The declaration of a variable is indistinguishable , Can point to arbitrary data . for example :

var x = 100;
x = "abc";
x = true;
x = [];
x = function(){}
x = new Object();
x = {};

in addition ,JS There is no syntax error in declaring variables with the same name multiple times in , for example :

/* 2. Definition of variables  */
var s = "Hello"; // var s; s="Hello";
var s = 123; // var s; s=123;  Declare the variable a second time x No entry into force 
alert( s ); //123

JS It's strictly case sensitive !

JS Operator

JS and Java The operators in are roughly the same , for example :

 Arithmetic operator : +,-,*,/,%,++,--
 Assignment operator : =,+=,-=,*=,/=,%=
 Comparison operator : ==,!=,>,>=,<,<=
 An operator : & , |
 Logical operators : && ,||   ( false &&  expression , true ||  expression  )
 Pre logical operators : ! (not)
 Ternary operator :  expression  ?  expression  :  expression 
...

JS sentence

JS And Java The sentences in are also roughly the same

1、if Branching structure

if Branches are used to perform different actions based on different conditions . The syntax is as follows :

if ( Conditions  1){
     When conditions  1  by  true  Code executed at 
}else if ( Conditions  2){
     When conditions  2  by  true  Code executed at 
}else{
     When conditions  1  and   Conditions  2  Not for  true  Code executed at 
}

2、switch sentence

Use switch Statement to select one of the blocks of code to execute . The syntax is as follows :

switch(n){
    case 1:
         Execute code block  1
        break;
    case 2:
         Execute code block  2
        break;
    ...
    default:
         And  case 1  and  case 2  Code that doesn't execute at the same time 
}

Execution principle : First set the expression n( It's usually a variable ). Then the value of the expression will match each of the case Compare the values of . If there is a match , Then it is related to the case The associated block of code is executed . Please use break To prevent code from automatically moving to the next case function .

3、for Loop statement -- Loop code block a certain number of times

for The syntax structure of the loop is as follows :

for ( sentence  1;  sentence  2;  sentence  3){
     Code block executed 
}

4、while loop -- Loop the code block when the specified condition is true

JS in while Cycles are also divided into while and do/while loop , The following is while Cyclic grammatical structure :

while ( Conditions ){
     Code to execute 
}

while Loop will loop through a block of code when the specified condition is true .

Case study 1:if Branch case : Receive user input scores , Judge the grade of your grade

80~100( Include 80, Also include 100)  good 
60~80( Include 60, But does not include 80)  secondary 
0~60( Include 0, But does not include 60)  fail, 
 Other values   Incorrect input 

The code implementation is as follows :

propmt( Parameters 1, Parameters 2 ) function : A message input box pops up on the page , Parameters received 1 It is the prompt content displayed in the pop-up box , User input content , Will be returned directly as the return value of the function .

Parameters 2, Is the default value in the input box , You can modify

var score = prompt(" Please enter your score : ");
if( score >= 80 && score <=100 ){
    alert(" Your grades belong to :  good !");
}else if( score >= 60 && score < 80 ){
    alert(" Your grades belong to :  secondary !");
}else if( score >= 0 && score < 60 ){
    alert(" Your grades belong to :  fail, !");
}else{
    alert(" Your input is wrong ,  Please re-enter !");
}

Case study 2:switch Sentence case — Implement a simple calculator :

It can receive two values and an operator from the user (+、-、*、/), According to the different operation symbols , Perform different operations on two values .

The code implementation is as follows :

//1. Receive user input values and operators ,  Space between 

var str = prompt(" Please enter the value 1、 Operator 、 The number 2, Space between :"); //"10 + 5"

//2. Cut the user input ( Cut with space as a separator )

var arr = str.split(" "); // ["10", "+", "5"]

var num1 = arr[0] - 0 ;
var opt = arr[1];
var num2 = arr[2] - 0 ;
//3. adopt switch Branch implementation calculator 
switch( opt ){
    case "+":
        alert( " The sum of two numbers is : "+( num1+num2 ) );
        break;
    case "-":
        alert( " The difference between two numbers is : "+( num1-num2 ) );
        break;
    case "*":
        alert( " The product of two numbers is : "+( num1*num2 ) );
        break;
    case "/":
        alert( " The quotient of two numbers is : "+( num1/num2 ) );
        break;
    default:
        alert( " The operator you entered is incorrect ,  Please re-enter !" );
}

Case study 3:for Loop statement case

Traverse 1\~100 Between all the integers , seek 1\~100 The sum of all integers between , And output to the console ;

The code implementation is as follows :

//--------------------------------------
var i = 1;
var sum = 0;
while( i <= 100 ){
    sum += i;
    i++;
}
alert( "1~100 The sum of all integers between is : "+sum );
//--------------------------------------
var sum = 0;
for( var i=0; i<=100; i++){
    sum += i;
}
alert( "1~100 The sum of all integers between is : "+sum );
//--------------------------------------

Case study 4:while Loop statement case

Traverse the elements in the following array , Output the element to the console .

var arr = [123, "abc", false, new Object() ];

The code implementation is as follows :

var arr = [123, "abc", false, new Object() ];
var index = 0;
while( index < arr.length ){
    console.log( arr[index] );
    index++;
}
for( var i=0; i<arr.length; i++ ){
    console.log( arr[i] );
}

JS Array

Array Object is used to store multiple values in a single variable .

JS Array declaration method 1 :

// Declare an empty array , The length is zero 
var arr1 = [];
// Declare an array , And set the initial value for the array 
var arr2 = ["Hello", 111, false, new Object() ];

JS Array declaration method 2 :

// Declare an empty array , The length is zero 
var arr3 = new Array();
// Declare an array , And set the initial value for the array 
var arr4 = new Array("Hello", 111, false, new Object());

Details in arrays :

(1)JS The array in can store any type of data

(2)JS The length of the array in can be changed arbitrarily

var arr1 = [];
console.log(" The length of the array here is : "+arr1.length ); // 0
arr1.length = 5;
console.log(" The length of the array here is : "+arr1.length ); // 5
arr1[9] = "a";
console.log(" The length of the array here is : "+arr1.length ); // 10
arr1[99] = "b";
console.log(" The length of the array here is : "+arr1.length ); // 100

JS function

A function is a functional block of code , It can be called repeatedly

Functions are blocks of code wrapped in curly braces , Key words used earlier function.

JS The way to declare a function in is :

function  The name of the function ([ parameter list ]){
     The body of the function 
}

perhaps :

var  Variable name / Function name  = function([ parameter list ]){
     The body of the function 
}

Call function : The name of the function ([ parameter list ]);

Comprehensive practice

( Do it yourself ) Declare a function fn, Implement in a function : Traverses two specified values ( for example 1 and 100) Integer between , It will be 3 The value of the multiple of is stored in an array , And return the array to .

1、 Statement fn function

// Make a statement fn function , Receive two parameters 
function fn(x,y){
    // Declare an array , For storage is 3 The number of multiples of 
    var arr = [];
    // loop x To y Between all the integers 
    for(var i=x,j=0;i<y;i++){
        // Judge i( The integer currently traversing ) Is it 3 Multiple 
        if(i%3==0){
            arr[j] = i; // If it is , Will i Deposit in arr Array 
            j++; //j Self increasing 
        }
    }
    return arr; // return arr Array 
}

2、 call fn function , obtain 1\~100 Between 3 An array of multiples of

var arr = fn(1,100);

3、 Traversing elements in an array , Output on the web ( Tips : document.write(" Output content ") )

for(var i=0;i<arr.length;i++){
    document.write(arr[i]+" ");
}

DOM operation

DOM: Document Object Model, Document object model , In fact, that is JS Specifically for visiting html Elements provide a set of API.

Case study : Light switch

Click on the light to turn on / Turn off the lights , The code implementation is as follows :

var flag = "off"; // The state of the marker lamp , off It means that the light is off !
function changeImg(){
    // obtain img Elements , Back to a JS object 
    var oImg = document.getElementById("img1");
    if( flag == "off" ){ // It means that the light is off before , After clicking, you need to open 
        oImg.src = "imgs/on.gif"; // The lights are on 
        flag = "on"; // Update the light status to on, It means the light is on 
    }else{ //on, It means that the light is on before , After clicking, you need to close 
        oImg.src = "imgs/off.gif"; // The lights are off 
        flag = "off"; // Update the light status to off, It means the light is off 
    }
}

Case study : Secondary linkage drop-down box

var data = {
  " The Beijing municipal ": [" Haidian District "," Chaoyang District "," Fengtai District "],
  " Hebei Province ": [" shijiazhuang "," Tangshan "," qinhuangdao "],
  " Liaoning Province ": [" shenyang "," dalian "," Anshan "],
  " Shandong Province ": [" Qingdao "," jinan "," yantai "]
}
/*  practice 2:  Realize the two-level linkage drop-down box  */
function selectCity(thisobj){
    //1. Get the province selected by the user 
    var prov = thisobj.value;
    //2. Get a list of all the cities in the province according to the province   The Beijing municipal 
    var arrCity = data[prov];
    //console.log(arrCity);
    
    //3. All the cities in the province   As option Option fills in to the second select In the list 
    //>> Get the second select
    var oCity = document.getElementById("city");
    
    //>> First clear the list of cities corresponding to the previous province 
    // Mode one 
    //oCity.innerHTML = "<option>-- Select the city --</option>";
    
    // Mode two  JS Features of arrays in 
    var opts = oCity.getElementsByTagName("option");
    // Loop traversal ,  Delete each one one by one option
    var len = opts.length;
    for(var i=0; i<len-1; i++){
        oCity.removeChild(opts[1]);
    }
    
    // Haidian District  --> <option> Haidian District </option>
    for(var i = 0; i<arrCity.length; i++){
        var oOpt = document.createElement("option");
        oOpt.innerHTML = arrCity[i];
        oCity.appendChild(oOpt);
    }
}

Case study : Table alternate color

practice 1: Click the button to make the table row alternate color

/*  practice 1: Click the button to make the table row alternate color  */
function changColor(){
    // Get all tr An array of elements 
    var aTr = document.getElementsByTagName("tr");
    // Loop traversal tr Every one of the arrays tr Elements 
    for(var i=1; i<aTr.length; i++){
        if(i%2 == 0){// p. ( accidentally ) A few lines , Set to one
            aTr[i].className = "one";
        }else{// accidentally ( p. ) A few lines , Set to one
            aTr[i].className = "two";
        }
    }
}

practice 2: When you hover over a table row element , Color the current line ; When the mouse moves away from the element , Restore default style

/*  practice 2: When you hover over a table row element , Color the current line ; When the mouse moves away from the element , Restore default style 
   onload: When the page is loaded with all the html After the element , Execute now function  */
window.onload = function(){
    // Get all tr An array of elements 
    var aTr = document.getElementsByTagName("tr");
    for(var i=1; i<aTr.length; i++){
        var classNameTemp;
        // When the cursor moves into an element 
        aTr[i].onmouseover = function(){
            classNameTemp = this.className;// Remember before the change class
            this.className = "hover";
        }
        // When the cursor moves out of the element 
        aTr[i].onmouseout = function(){
            this.className = classNameTemp;
        }
    }
}

summary :JS How to get elements in

document It's a js object , Used to indicate the present html Webpage . When the browser loads the entire html After the web page , Will use document Object represents the whole of html Webpage !

document.getElementById( id value  ) --  By element id value , Get an element . Returns the... That represents the element js object .

<div id="div1">xxxx</div>
// obtain id by div1 The elements of 
var oDiv1 = document.getElementById("div1");
//oDiv1 It's a js object , Represents the acquired div Elements 

document.getElementsByTagName(  Element name  ) --  Get all the named elements in the current document by element name , It returns an array , It contains all the elements with the specified name .

document.body --  Get the body Elements

element.parentNode --  Get the parent of the current element .element Represents the current element

summary :JS How to add, delete and modify elements

document.createElement(  The element name  ) --  Creates an element with the specified name based on the element name , That represents the new element js object

parent.appendChild( child ) --  Add child elements through parent elements , among parent Represents the parent element ,child Represents a child element

parent.removeChild( child ) --  Delete the child element through the parent element , among parent Represents the parent element ,child Represents a child element

element.innerHTML --  Get the... Of the current element html Content ( Everything from the start tag to the end tag ), Or set the current element's html Content ( If there is content inside the element , The original content will be covered )

<div id="div1">
     This is a div Elements ...
    <span> This is a span Elements </span>
</div>
// obtain div Elements 
var oDiv1 = document.getElementById("div1");
oDiv1.innerHTML;// obtain div Content of element 

element.value -- Get the form item element value Content , Or set the form item element's value value ( If the element has value value , The original value will be overridden )

Extended content

JS Common events in

event describe
onclick After the binding element is clicked , Trigger execution immediately onclick Specified function
onchang When the binding element changes , Trigger execution immediately onchang Specified function
onmouseover When the mouse moves over the element , Immediately triggered onmouseover Specified function
onmouseout When the mouse moves away from the element , Immediately triggered onmouseover Specified function
ondblclick After the bound element is double-click , Trigger execution immediately ondblclick Specified function
onload After the browser has loaded all the elements in the page , Execute now onload Specified function

unit03-jQuery

jQuery brief introduction

What is? jQuery( understand )

jQuery: JavaScript Query JS Inquire about

jQuery It's a lightweight door 、 Free and open source JS function library ( Namely JS A simple framework for )

jQuery Can greatly simplify JS Code

jQuery The core idea of :“ Write less , But more ”


A lightweight : It means that a technology or framework has a relatively low degree of intrusion into code or program .

Or the less dependent the code is on the technology , The lighter the technology is . The more dependent on this technology , The heavier the technology is .

jQuery In essence, it contains many functions JS file , If you want to be in a certain HTML Use this JS Functions in the file , You have to JS File import to HTML in ( Want to use jQuery, You have to introduce jQuery Function library file of , It's just one. JS file )


jQuery The advantages of ( understand )

(1) Can greatly simplify JS Code

(2) Can be like CSS Selectors get html Elements

css Get all the div, to div Add the style :

div{ css attribute ... }

jQuery Get all div, to div Add border style :

$("div").css("border", "2px solid red");
JS obtain id by div1 The elements of : document.getElementById("div1")
jQuery obtain id by div1 The elements of : $("#div1")

(3) It can be modified by css Property controls the effect of the page

(4) Can be compatible with common browsers

such as : JS Medium innerText attribute 、removeNode() function 、replaceNode( ) function These functions are not available in some browsers .

jQuery The corresponding functions are provided in ( text function 、remove function 、replaceWith function )

Popular browsers : Google browser 、 Firefox 、 Apple chrome 、 Opan browser, etc

jQuery introduce

jQuery Function library file is a common JS file , introduce jQuery And introduction JS It's the same way to file .

<!--  In the use of jQuery Before , You have to introduce jQuery Function library file of  -->
<script src="js/jquery-1.8.3.js"></script>

In the introduction of jQuery Function library file , If the file import path is wrong , Will cause file import failure , Here's the picture :

image-20200803120733230

Document ready event function

<head>
<meta charset="UTF-8">
<!--  In the use of jQuery Before , You have to introduce jQuery Function library file of  -->
<script src="js/jquery-1.8.3.js"></script>
<script>
    //1. obtain id by demo Of h1 Elements 
    var h1 = document.getElementById( "demo" );
    //2. obtain h1 Content in the element ( innerHTML )
    alert( h1.innerHTML );
</script>
</head>
<body>
    <h1 id="demo">jQuery An example of the introduction of ...</h1>
</body>

Problem description : The code above is executed , Will report a mistake :

image-20200803120845996

Reason to describe : In the execution of the acquisition id by demo The element is , h1 The element has not been loaded by the browser yet , So you can't get it h1 Elements .

Solution one :

take script Label moved to body Inside , That is to say h1 After element

In this way, when the browser loads , Will load first h1 Elements , Then execute the acquisition h1 The code for the element , Because it's getting h1 Before element ,h1 The element has been loaded by the browser , So we can get it later !

Code example :

<body>
    <h1 id="demo">jQuery An example of the introduction of ...</h1>
    <script>
        //1. obtain id by demo Of h1 Elements 
        var h1 = document.getElementById( "demo" );
        //2. obtain h1 Content in the element ( innerHTML )
        alert( h1.innerHTML );
    </script>
</body>

Solution two :

Put the code to get the element in the document ready event function , The document ready event function will load all the html After the element ( That is, after loading the last one html Element time ) Execute now .

Because all the elements in the current page are loaded ,h1 The element must have been loaded , At this point, you can get h1 The element is bound to get .

<head>
<meta charset="UTF-8">
<!--  In the use of jQuery Before , You have to introduce jQuery Function library file of  -->
<script src="js/jquery-1.8.3.js"></script>
<script>
    $(function(){
        //1. obtain id by demo Of h1 Elements 
        var h1 = document.getElementById( "demo" );
        //2. obtain h1 Content in the element ( innerHTML )
        alert( h1.innerHTML );
    });
</script>
</head>
<body>
    <h1 id="demo">jQuery An example of the introduction of ...</h1>
</body>

Solution three :

Put the code to get the element in a custom function , And bind the function to h1 Element click event , When we click h1 Element will execute the custom function , When the function is executed h1 Elements , You can get it at this time h1 Elements .

<head>
<meta charset="UTF-8">
<!--  In the use of jQuery Before , You have to introduce jQuery Function library file of  -->
<script src="js/jquery-1.8.3.js"></script>
<script>
    function fn1(){
        //1. obtain id by demo Of h1 Elements 
        var h1 = document.getElementById( "demo" );
        //2. obtain h1 Content in the element ( innerHTML )
        alert( h1.innerHTML );
    }
</script>
</head>
<body>
    <h1 id="demo" onclick="fn1()">jQuery An example of the introduction of ...</h1>
</body>

summary : When to use the document ready event function ?

If you get the element , Get the timing of code execution for the element , Even earlier than the element itself , If the element is not loaded, get it , It must be impossible to get .

You can put the code that gets the element in the document ready event function , After the browser loads the entire web page , The document ready event function is executed , At this point, all the elements are loaded , If you take any element, you can get !

jQuery Provided document ready event function ( Abbreviation form ):

<script>
    $(function(){
        // Load the entire... In the browser html Execute immediately after the web page 
    });
</script>

The complete way to write it is :

<script>
    $(document).ready(function(){
        // Load the entire... In the browser html Execute immediately after the web page 
    });
</script>

JS The document ready event function is also provided for us , It's written as :

<script>
    window.onload = function(){
        // Load the entire... In the browser html Execute immediately after the web page 
    }
</script>

jQuery Selectors ( a key )

Basic selector

(1) Element name selector 
$("div") --  Check all div Elements 
$("span") --  Check all span Elements 

(2)class/ Class selectors 
$(".s1") --  Select all class The value is s1 The elements of (class The value is s1 The element of can be any element )
$("span.s1") --  Select all class The value is s1 Of span Elements 

(3)id Selectors 
$("#one") --  Choose id by one The elements of 

(4) Multi element selector 
$("div,span,.s1,#one") --  Check all div Elements , And all span Elements , And all class The value is s1 The elements of , as well as id by one The elements of 

Hierarchy selector

$("div span") --  Select all div All inside span Elements 
$("#one span") --  Choose id by one All of the elements inside span Elements 

$("#two+span") --  Choose id by two The next to the element of span Brother element 
$("#two").next("span") --  Choose id by two The next to the element of span Brother element 
$("#two").prev("span") --  Choose id by two The element of is immediately ahead of span Brother element 

$("#two~span") --  Choose id by two All of the following elements of span Brother element 
$("#two").nextAll("span") --  Choose id by two All of the following elements of span Brother element 
$("#two").prevAll("span") --  Choose id by two All of the elements in front of span Brother element 

$("#two").siblings("span") --  Choose id by two Before the element of 、 After all span Brother element 

Basic filter selector

(1)  Choose the first one div Elements 
$("div:first")
$("div:eq(0)")
$("div").eq(0)

(2)  Choose the last div Elements 
$("div:last")
$("div:eq(-1)")
$("div").eq(-1)

(3)  Select the first n+1 individual div Elements (n Starting from scratch )
$("div:eq(n)")
$("div").eq(n)

Comprehensive case

Create table elements

practice 1: Create a single row, single column table

function createTable1(){
    //1. Create a table Elements 
    var $tab = $("<table></table>");
    //2. Create a tr Elements 
    var $tr = $("<tr></tr>");
    //3. Create a td Elements ,  And for td Add content 
    var $td = $("<td></td>");
    $td.html("Hello TD~~");
    //4. take td Add to tr Element interior 
    $tr.append( $td );
    //5. take tr Add to table Element interior 
    $tab.append( $tr );
    //6. take table Add to body Element interior 
    $("body").append( $tab ); 
    
    //$("body").append( "<table><tr><td>Hello~~TD...</td></tr></table>" );
}

practice 2.1: Create a single line 6 List of tables

function createTable2(){
    //1. Create a table Elements 
    var $tab = $("<table></table>");
    //2. Create a tr Elements 
    var $tr = $("<tr></tr>");
    for(var i=0;i<6;i++){ 
        //3. Create a td Elements ,  And for td Add content 
        var $td = $("<td></td>");
        $td.html("Hello TD~~");
        //4. take td Add to tr Element interior 
        $tr.append( $td );
    }
    //5. take tr Add to table Element interior 
    $tab.append( $tr );
    //6. take table Add to body Element interior 
    $("body").append( $tab ); 
}

practice 2.2: establish 5 That's ok 6 List of tables

function createTable2(){
    //1. Create a table Elements 
    var $tab = $("<table></table>");
    for(var j=0;j<5;j++){ // The outer loop : Control the number of lines 
        //2. Create a tr Elements 
        var $tr = $("<tr></tr>");
        for(var i=0;i<6;i++){ // Inner circulation : Control the number of columns 
            //3. Create a td Elements ,  And for td Add content 
            var $td = $("<td></td>");
            $td.html("Hello TD~~");
            //4. take td Add to tr Element interior 
            $tr.append( $td );
        }
        //5. take tr Add to table Element interior 
        $tab.append( $tr );
    }
    //6. take table Add to body Element interior 
    $("body").append( $tab ); 
}

practice 3: Create a table with specified rows and columns

function createTable3(){
    // Get the number of rows and columns entered by the user (js The way )
    //var rows = document.getElementById("rows").value;
    //var cols = document.getElementById("cols").value;
    var rows = $("#rows").val();
    var cols = $("#cols").val();
    console.log(rows+" : "+cols);
    //1. Create a table Elements 
    var $tab = $("<table></table>");
    for(var j=0;j<rows;j++){ // The outer loop : Control the number of lines 
        //2. Create a tr Elements 
        var $tr = $("<tr></tr>");
        for(var i=0;i<cols;i++){ // Inner circulation : Control the number of columns 
            //3. Create a td Elements ,  And for td Add content 
            var $td = $("<td></td>");
            $td.html("Hello TD~~");
            //4. take td Add to tr Element interior 
            $tr.append( $td );
        }
        //5. take tr Add to table Element interior 
        $tab.append( $tr );
    }
    //6. take table Add to body Element interior 
    $("body").append( $tab ); 
}

Imitation QQ The friends list

/**  adopt jQuery Realize imitation QQ List friends list  */
function openDiv(thisobj){ //thisobj It's a js object  -- Turn into --> jQuery object 
    // Turn off the other three groups first (  Divide the other three groups of div Set as hidden  )
    $("table span").not(thisobj).next("div").hide(); //css("display", "none")
    // Find the list of friends in the group according to the group you click on ,  Switch the display status of friends list 
    $(thisobj).next("div").toggle(); // If the element is displayed, switch to hidden ,  If hidden, switch to show 
}

Simulation of employee information management system

practice 1: Add employee information

function addEmp(){
    //1. Get the employee information to be added (id, name, email, salary)
    var id = $("#box1 input[name='id']").val().trim();
    var name = $("#box1 input[name='name']").val().trim();
    var email = $("#box1 input[name='email']").val().trim();
    var salary = $("#box1 input[name='salary']").val().trim();
    console.log(id+" : "+name+" : "+email+" : "+salary);
    
    //2. Verify employee information 
    //2.1. Can't add empty employee information !
    if( id == "" || name == "" || email == "" || salary == "" ){
        alert( " Can't add empty employee information !" );
        return;
    }
    
    //2.2. Added employees id Can't repeat ! (id=3)
    // Get all tr Elements ,  And go through all the tr Elements 
    var flag = false; //false Express id It doesn't exist !!!
    $("table tr").each(function(){ //this(JS object ) Represents the currently traversed element  
        // this -- Convert to jQuery object --> $( this ) 
        var _id = $(this).find("td:eq(1)").text();
        // Take the user's input id And the current employee's id Compare 
        if( id == _id ){ // As long as there is an equality , Just explain id Already exists , Stop adding 
            alert(" The employee you entered ID Already exists ,  Please re add !");
            flag = true; //true Express id Already exists !!
            //return;  It's here return Cannot terminate program execution 
        }
    });
    if( flag ){ //true Express id Already exists !!
        return;
    }
    //3. Add employee information to the page ( Add to table in )
    //>> Create a tr Elements 
    var $tr = $("<tr></tr>");
    //>> establish 5 individual td Elements , And add employee information to td in 
    var $td1 = $("<td><input type='checkbox'/></td>"); // Check box 
    var $td2 = $("<td>"+id+"</td>"); //ID
    var $td3 = $("<td>"+name+"</td>"); //name
    var $td4 = $("<td>"+email+"</td>"); //email
    var $td5 = $("<td>"+salary+"</td>"); //email
    //>> take td Element added to tr in 
    $tr.append( $td1 ).append( $td2 ).append( $td3 ).append( $td4 ).append( $td5 );
            
    //>> take tr Element added to table in 
    $("table").append( $tr );
}

practice 2: Delete employee information

function delEmp(){
    //1. Get the selected employee's tr That's ok  ( Get all selected check boxes )
    //$("input:checked").parents("tr").remove(); // It will be deleted together with the header 
    $("input:checked").parent("td").parent("tr").remove();
}

practice 3: Modify employee information ( Do it yourself )

practice 4: Select all or none of them

function checkAll(){
    //1. Gets the selected state of the select all check box (  Choose (true)?   No choice (false)? )
    var isCheck = $("#all").prop("checked"); //true|false
    //2. Get all the normal checkboxes ,  Set the selected state of all check boxes to all normal check boxes 
    $("input[type='checkbox'][id!='all']").prop("checked",isCheck);
}

jQuery summary

html Element operation

1、 Create elements

$("<div></div>") --  Create a div Elements , Back to a jQuery object , Represents the created div Elements 
$("<div>xxxx</div>") --  Create a content containing div Elements , Back to a jQuery object , Represents the created div Elements 

2、 Add child elements

$parent.append( $child ) --  The parent element calls the method to add the child element 
$("body").append( "<div> I'm new here ...</div>" ); --  Go to body The element is appended with a div Subelement 

3、 Remove elements

$("div").remove() --  Delete all div Elements 

JS Delete all div Elements :
// Get all div Elements ( It's all back div Array of components )
var divArr = document.getElementsByTagName("div"); //div Array 
// Traverse div Array , Delete each one in turn div Elements 
var len = divArr.length;
for(var i=0;i<len;i++){
    // Delete the current element through its parent element ( Always delete the first )
    divArr[0].parentNode.removeChild( divArr[0] );
}

4、 Replacement elements

$("div").replaceWith("<p> I'm here to replace …</p>")

html Operation of element content and value

<div>
       This is a div11 Elements 
    <span> This is a span Elements </span>
     This is a div1111 Elements 
</div>
<input type="text" name="user"/>

1、html() function ( Be similar to js Medium innerHTML attribute )

-- Used to get or set the content of an element , For example div、span、p、h1~h6、table、tr、td、form Set the content with the elements

$("div").html() --  Get all div The first of div The content of 
$("div").html("xxxx") --  For all div Set contents 

2、text() function ( Be similar to js Medium innerText attribute ,innerText Not compatible in some browsers )

-- Used to get or set the text content of an element

$("div").text() --  Get all div All the text content in 
$("div").text("xxxx") --  For all div Set text content 

3、val() function ( Be similar to js Medium value attribute )

-- Gets or sets the... Of the form item element value value (input/select/option/textarea)

$("input").val() --  Get all input The first of the elements input Elemental value value 
$("input").val( value ) --  For all the input Element settings value value 

Element attributes and css Attribute operation

<input type="text" name="username" id="inp"/>

1、prop() function -- Used to get or set the attribute value of an element

stay jQuery1.6 This function is available only after the version ,1.6 Previous version jQuery have access to attr() function

$("input[type='checkbox']").prop("checked")
//  obtain input Check box selection status ,  return true Indicates that the check box is selected , return false Indicates that the check box is unselected 
$("input[type='checkbox']").prop("checked", true)
//  Set the matching check box element to the selected state 

$("#inp").prop("name"); // obtain id by inp Elemental name Property value ,  return useranme
$("#inp").prop("name","user"); // by id by inp The element settings of name Property value , name The property value becomes user

2、css() function -- Used to get or set elements css Property value

$("#div1").css("width") --  obtain id by div1 Width of element 
$("#div1").css("width","200px") --  Set up id by div1 The width of the element is 200px
$("#div1").css({
    "width" : "200px",
    "height" : "150px",
    "border" : "5px solid red",
    "background" : "pink"
}); //  by id by div1 The width of the element is set to 200px、 The height is 150px、 Border and background color, etc 

Other functions

1、each() function

$(selector).each(function( index,element ){})
// each() Functions can traverse $(selector) All elements selected by the selector ( That is, each time the selector selects an element from the selected element , And implement function  function )
// function Medium index --  The subscript of the element that represents the traversal 
// function Medium element --  Represents the element that is currently traversing ( It can also be done through this obtain )

Example :

$("table tr").each(function(){
    // Get the contents of the second cell from the current row ( The current line of id value )
    var tempId = $(this).find("td").eq(1).html();
    // Take the user's input id  and   In each line id Value comparison 
    if( id == tempId ){
        alert(" Add failure ,id Already exists !");
        flag = true; //id There is , to update flag Value ,true It means that there is already !
    }
});

2、show()/hide() function

show() -- Set the element from hidden to displayed

$("div").show() --  Set all div The element is display 

Equivalent to :

$("div").css("display", "block");

hide() -- Set the element from show to hide

$("div").hide() --  Set all div Elements are hidden 

Equivalent to :

$("div").css("display", "none");

2、toggle()/slideToggle()

toggle() -- Switch the display state of the element , If the element is displayed , Switch to hide , Otherwise, switch to display

slidToggle() -- Switch the display state of the element , If the element is displayed , Switch to hide , Otherwise, switch to display , Switch to display as drop-down state , Hidden as a contraction state .

Extended content

Binding click events for elements

Take the click event as an example , The way to bind a click event to an element is :

The way 1(js edition ):

<script>
  function fn(){
    alert("input The button is clicked ...");
  }
</script>
<body>
    <input onclick="fn()" type="button" value=" Am I ~!" />
</body>

The way 2(js edition ):

<script>
    window.onload = function(){
        // obtain id by btn The elements of 
        var btn = document.getElementById("btn");
        btn.onclick = function(){
            alert("input The button is clicked ...");
        }
    }
</script>
<body>
    <input id="btn" type="button" value=" Am I ~!" />
</body>

The way 3(jQuery edition ):

<script>
$(function(){
    // When you click btn Button , Trigger the click event to execute the function 
    $("#btn").click( function(){
        alert("input The button is clicked ...");
    });
});
</script>
<body>
    <input id="btn" type="button" value=" Am I ~!" />
</body>

js Objects and jQuery Conversion of objects to each other

adopt JS The way to get the element , The return is JS object ,JS Object can only call JS Property or function of

adopt jQuery Selector gets element , The return is jQuery object ( The structure is like a collection ),jQuery Object can only call jQuery Property or function of .

If existing JS object , But we need to call jQuery Property or function of , Can be JS Conversion of objects jQuery object ;

If existing jQuery object , But we need to call JS Property or function of , Can be jQuery Conversion of objects JS object ;

版权声明
本文为[one who tries not to offend anybody]所创,转载请带上原文链接,感谢