Basic knowledge of html5, final review

Table of contents

1.1 Web system architecture

1. C/S (Client/Server) structure

1.2 Browser

1. Rendering Engine

2. Javascript engine

1.3 Web related concepts

1、URL(Uniform Resource Locator )

2. Hyperlink

3. Website

4. Web page

5. Home page

6. Static web pages

7. Dynamic web pages

8. Web Design Principles

9. Web Design Technology

2.2 Label basics

2.2.1 Label syntax

1. Double label

2. Single label

3. Properties

2.2.2 Basic Labels

1. Metadata

2. Form

3.1 CSS Overview

3.1.1 Understanding CSS

3.1.2 How to use CSS

3.1.3 Basic concepts of CSS

1. Unit

2. Color value

3. Inheritance

4. Cascading

5. Importance

6. Element type

7. Document flow

3.3 CSS selectors

1. Selector type

3.5 CSS Common Properties

1. Font properties

2. Text

8. Overflow

10. Floating

3.6 Box Model

1. The basic concept of the box model

2. Multi-box margin merge problem

4.1 Introduction to JavaScript

1. JavaScript concept

2. Features and functions of JavaScript

3. JavaScript code embedding

4.2 JavaScript Basic Syntax

4. Operators and expressions

4.4 JavaScript commonly used objects

1. The concept of objects

2. Use of events

3. Common objects

1) window object

2) window prompt dialog box

3) document object

5.1 Basics of Responsive Web Design

1. Introduction to Responsive Web

2. New features of HTML5

3. Basic syntax of HTML5

4. HTML5 semantic tags

5. New features of CSS3

5.2 Text-based web page design

1. Commonly used text tags in HTML5

2. CSS font style properties

3. The @font-face rule of CSS3

4. Multi-column Layout

5. CSS Text Appearance Properties

7. Web Font Icons

8. CSS navigation bar

5.3 Graphic and text web page design

1. HTML5 commonly used image tags

2. CSS background settings

3. Box Shadow

4. CSS3 Gradients

5. Rounded border

6. CSS3 Transitions

7. CSS3 deformation

8. CSS3 animation

9. CSS sprite technology

5.4 HTML5 form application

 HTML5 form validation     

5.5 HTML5 Canvas

5.6 Audio and Video

1. Video

2. HTML DOM Video object

3. Audio

5.7 Responsive web design

1. Basic concepts

(2) Media queries

2. Responsive design

5.8 Bootstrap front-end tools

1. Introduction to Bootstrap

Implement Responsive

2. Important controls


1.1 Web system architecture

Understanding structure is a very important way we learn many courses.

The Web application project itself is a software system, and it also has its own structure, that is, the system architecture. There is a course "Software Architecture" dedicated to this problem.

The system architecture is a model that integrates various viewpoints and is used to describe the entire system completely. Through the system architecture, the basic architecture of a software system can be understood. Common system architectures include C/S structure and B/S structure.

1. C/S (Client/Server) structure

First, understand the workflow of C/S. The server stores various resources. We send resource requests through the network on the client side, receive and display the content of the response from the server side. As shown below:

Browsing web content is the main service provided by the Internet. It uses the HTTP protocol (HyperText Transfer Protocol) to transmit web page content written in HTML (Hyper Text Markup Language) on the Internet, so as to exchange information.

Its specific working steps are as follows:

☆ Input the URL through the client browser to send a service request to the WEB server;

☆ The server parses the URL requested by the browser and finds the corresponding webpage file;

☆ The webpage contains scripts such as JavaScript, which will be downloaded to the client together with the HTML document; if there are programs such as ASP embedded in the webpage, the server will execute these programs and send the running results to the client in the form of HTML tags;

☆ The browser interprets the HTML document and displays the result.

Hypertext Transfer Protocol (HTTP) is a communication protocol between WEB browser and WEB server application layer. The HTTP session process consists of 4 steps:

☆ Establish a link (connection);

☆Send request (request);

☆Response request (response);

☆ Close the link (close).

Under the C/S structure, different services need to install different client software, which in turn occupies a lot of system resources. In addition, it has some other disadvantages. For example, A needs to process files on B’s computer, but B’s computer does not have similar software installed, so it has to be downloaded first, which is very inconvenient, and it needs to be downloaded again after the software is upgraded. Therefore, a new method is needed to solve this problem, so there is a new B/S structure.

2. B/S (ie Broswer/Server) structure

The B/S structure is the browser/server structure, which solves the inconvenience caused by the C/S structure, and can complete all services (such as QQ, mail, etc.) through the browser. Since a certain browser is usually installed in the operating system, more system resources can be saved in this way. At the same time, there is no need to re-download the upgrade of various service software functions, just refresh the webpage. However, B/S also has some shortcomings, such as relatively weak operation stability and fluency, and relies heavily on the network.

After explaining the C/S architecture and B/S architecture, in order to make everyone more aware of their respective characteristics, the following is a comparative description of them, as shown in the table.

1.2 Browser

Everyone has this experience: when surfing the Internet, they usually send request information through the browser, such as URL address, keywords, etc., and at the same time check the response information of the Internet through the browser. It can be seen that the browser is an important tool for the front end of the Web.

First of all, it must be clear that Web front-end development is based on the B/S structure, with the browser as the core. There are many types of existing browsers provided by different software vendors, and each has its own characteristics and advantages. The more commonly used browsers are IE, Firefox, Chrome, Opera and so on. So, what is the structure of the browser?

A browser is usually composed of a typesetting engine and a Javascript engine.

1. Rendering Engine

The typesetting engine, also known as the kernel, is used to render the content of the web page and convert the code of the web page into the final visible page. The kernels of different browsers are not the same.

1) The Trident kernel is the kernel used by the famous IE browser, and it is also the kernel used by many browsers, often referred to as the IE kernel.

2) The Gecko kernel is an open source browser kernel. The most mainstream browser using the Gecko kernel is Mozilla Firefox, so it is often called the Firefox kernel.

3) The WebKit kernel is the most promising emerging kernel, with very good performance and perfect support for W3C standards. Google's Chrome uses the Webkit kernel.

4) The Opera browser uses the Presto kernel, which also supports the W3C standard very well.

2. Javascript engine

The JavaScript engine is referred to as the JS engine for short. This engine is used to parse and execute JS programs, and its performance has a great impact on the loading speed of the entire web page.

1) Chakra (Chakra) engine is a new JavaScript engine enabled by IE9.

2) The SpiderMonkey engine is used in the Firefox browser.

3) The V8 engine is applied to the Chrome browser.

1.3 Web related concepts

1、URL(Uniform Resource Locator )

URL stands for Uniform Resource Locator, which is the address of each web page on the Internet. In layman's terms, a URL is a web address, specifying the location of an Internet resource.

The URL structure consists of three parts: http:// website address / directory path/file name.

Among them, "http://" is the protocol part of network access; "website address" is the address of the web server, which can be a domain name or IP address; "/directory path/file name" indicates the actual location of the resource stored on the server.

Example: http://www.cqvip.com/qk/83461A/200901/index.shtml

Visit index.shtml in the qk/83461A/200901 directory path of the Journal of Huaihua University website.

2. Hyperlink

Hyperlink is the main technology to realize hypertext. It points to WWW resources, such as web pages of different sites, other web pages of the same site, and other paragraphs of web pages.

The function of a hyperlink is that when browsing a web page, if you click a hyperlink with a mouse, you will jump to the resource pointed to by the hyperlink, and you can download information from the WEB.

The method of judging hyperlinks is very simple. When the cursor arrow is moved to the hyperlink with the mouse, the cursor will change into the shape of a hand.

3. Website

A website is a collection of complete information stored on a web server.

A website usually contains one or more web pages, which are linked together in a certain form to form a whole.

4. Web page

A webpage is an important part of a website. It is a page, which can be regarded as a single body and an element of the website. There can be text, pictures, sound, video, animation and other elements in the web page.

Among them, the text is the main body that constitutes the web page. The design of text elements includes font, typeface, color, paragraph setting and positioning, etc. The picture is the main means to realize the combination of pictures and texts on the web page. Commonly used graphics file formats are GIF, JPEG, PNG, and vector formats. When using pictures, the basic principle that should be grasped is that the graphics file is small, the quantity is small, the image quality is high, and the animation is used reasonably.

5. Homepage

The home page is also called the home page. It is a special web page, which is the starting point and aggregation point of the entire website.

The home page is also the entrance for visitors to browse a website.

6. Static web pages

A static web page means that no matter when and where the web page is viewed, the same screen and content will be displayed, and the user can only browse and cannot provide information to the website for the website to respond.

The programming languages ​​​​of static web pages include HTML, CSS, etc. HTML (Hypertext Markup Language) is the basis of web design, and it is also a specification for representing web pages. It defines the display format of web content through tags (or labels); CSS (Cascading Style Sheet) technology is an extension of HTML functions. Use It can design more expressive web pages.

Note: Adding relevant animations to a web page does not mean it is not a static web page.

7. Dynamic web pages

A dynamic webpage means that a webpage can respond dynamically according to the needs of users. Common dynamic web pages include message boards, forums, etc.

Commonly used webpage dynamic/special effect scripting languages ​​include JavaScript and VBScript. Among them, JavaScript is an object-based, dynamic, cross-platform, simple and safe scripting language. JavaScript is simple and powerful, mainly in:

(1) Making web page special effects;

(2) Realize client verification of form data;

(3) Realize the dynamic operation of the window.

8. Web Design Principles

Web design should master the following principles:

(1) The page strives to be concise: the page is concise and eye-catching, the color should not be too dark, and the pictures should not be too large;

(2) Cleverly arrange graphics and images: use the visual effects of pictures to make the page vivid and attract viewers;

(3) Good at learning information: referring to and applying ready-made information on the Internet can make web page production get twice the result with half the effort.

(4) The content is easy to understand: rich in content, easy to find, easy to read and understand.

(5) The page should be small, just right: to meet the needs of information volume and speed.

9. Web Design Technology

From the study of the concept part of static web pages and dynamic web pages, we know that web pages have their own structure, style and behavior. Wherein, the structure of the webpage is written by HTML language, the style of the webpage is defined and designed by CSS, and the behavior of the webpage is written by JavaScript. Therefore, the three major technologies of web design are HTML, CSS, and JavaScript, which will be introduced in detail in later chapters.

2.2 Label basics

2.2.1 Label syntax

HTML provides a set of tags to describe the content of the web page, such as head means the head of the web page, body means the main body of the web page, etc.

HTML tags consist of an independent word or word abbreviation, and these words or word abbreviations are required to be placed in "<>", such as <head>, <p>, etc. At the same time, tags are divided into double tags and single tags.

1. Double label

Double tags must have a start tag and an end tag. Between the two tags is the content to be displayed in the browser, and the start tag and the end tag should be used in pairs. "/" is added to the tag to indicate the end.

For example:

<p>

   A double tag indicates a paragraph and is an abbreviation for <strong>paragragh</strong>.

</p>

2. Single label

A single tag has no end tag, adding "/" at the end of the tag means self-closing. If it is not standardized, "/" can also be omitted, but it is recommended to use it in a standardized manner.

For example: <br/> (newline tag), <hr/> (label for drawing horizontal lines), <img src="" alt=""/> (display image tag), <input type="" /> ( Input tags, according to different type attribute values, will get different input elements. For example, text input box, button, etc.), etc.

3. Properties

Attributes are an important part of tags. Attributes can be used to make some special settings or make some additional supplements to tags. Attributes are divided into valued attributes and non-valued attributes. The attribute values ​​of valued attributes are wrapped in double quotes.

For example:

<img src="mypic.png" width="200px" height="200px" alt="I am a picture">

<input type="text" disabled/>

The parts written in the tag are attributes, among which src, width, height, alt, type, etc. are all valued attributes, and disable is a valueless attribute.

2.2.2 Basic Labels

1. Metadata

Metadata refers to the relevant information of the page, such as author, keywords, description, etc., which are set through the <meta> tag. Metadata will not be displayed on the client, but will be parsed by the browser. The <meta> tag can only be placed at the head of the document (between <head></head>), and metadata always appears in the form of "name/value" pairs. For example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
     <meta name="keywords" content="html,css,javascript,php">
     <title>大鸟教程</title>
     <meta http-equiv="content-type" content="text/html;charset=utf-8">
    </head>
    <body>
       学习元数据的使用
    </body>
</html>

Among them, the "name" in the "name/value" of the name attribute record of the <meta> tag, such as name="keywrods", the user can customize the name describing the web page information.

The content attribute records the "value" in the "name/value", such as content="html,css,javascript". Defines meta information related to the http-equiv or name attribute.

The http-equiv attribute is also the "name" in the "name/value" of the record, and associates the content attribute with the HTTP header.

2. Form

There are four main tags used to create a table: <table>, <tr>, <th>, <td>.

<table> and </table> are table tags used to define a table element;

<tr> and </tr> are row tags, used to define a row of the table;

<th> and </th> are cell tags, which are used to define the first row of cells in the table, the text in it is displayed in bold, and this row is optional;

<td> and </td> are cell tags, which are used to define the cells of the table. They must be placed inside <tr> and </tr> tags. There are as many pairs of <td> and </td> tags as there are cells in a row.

The syntax for creating a table is:

<table>

      <tr>

           <td>(<th>) first row and first column cell content</td>>(/<th>)

               ……

           <td>(<th>)The content of the cell in the nth column of the first row</td>>(</th>)

      </tr>

        ……

      <tr>

           <td>The content of the cell in the first column of row m</td>

               ……

           <td>Cell content in row m and column n</td>

      </tr>

</table>

3.1 CSS Overview

3.1.1 Understanding CSS

HTML tags have their own attributes, which are used to control the display effect of elements. As major browsers, such as Netscape and Internet Explorer, continue to add new HTML tags and attributes (such as font tags and color attributes) to the HTML specification, it becomes increasingly difficult to create sites where document content is clearly independent of the presentation layer of the document. more and more difficult. Therefore, as the element display effect control requirements change, the original attributes of the label cannot meet the requirements, so it is necessary to expand the attributes of the label to adapt to the change.

However, as HTML is a markup language, the core tag library of a certain version should remain relatively stable and should not be changed frequently.

In order to solve this problem, the World Wide Web Consortium (W3C), a non-profit standardization alliance, shouldered the mission of HTML standardization and created styles (Style) outside of HTML4.0. Therefore, the CSS (Cascading style sheets) cascading style sheet technology that extends the label attribute mechanism came into being.

In 1996, W3C proposed CSS1, the first cascading style sheet specification that defines HTML display styles, and it soon became a widely adopted standard. By 1998, W3C expanded on the basis of the original draft and established the CSS2 specification, which not only included the original forms and standards, but also had many enhanced functions. Now it has developed to the CSS3 specification, and its semantic capability is more powerful.

All major browsers support Cascading Style Sheets. CSS is used to control the style (that is, the display effect) of web page elements, such as font size, color, typography layout, etc. It can cooperate with HTML to design rich and colorful web pages. Writing style rules in CSS must follow the following grammatical rules.

          selector { declaration-list; } 

Among them, each statement in curly braces consists of colon-separated attribute-value pairs, and the declarations are separated by semicolons. Note that the last ";" cannot be omitted.

Assuming that the color of the text in the <h1> tag is set to red and the font size is set to 14 pixels, it needs to be set according to the following syntax.

                              

Special attention should be paid to adding a semicolon ";" after the last statement to avoid errors.

To understand and master CSS well, you need to accurately grasp the following three concepts.

(1) Elements. An element refers to a module representing the document format, which includes a start tag, an end tag and all the content contained in these two tags.

(2) Attributes. In an HTML document, an attribute refers to some aspect of an element's characteristics.

(3) RULES. A style rule consists of a selector and a declaration list (or declaration block), and a declaration block is a collection of "attribute: value" pairs (that is, declarations) that are used to control the display of web page elements.

In general, CSS has the following functions.

(1) Simplifies the design of the web page format and enhances the maintainability of the web page. It enhances the expressiveness of web pages and provides more effects to expand the content expression.

(2) The consistency of the website format is enhanced, and the workload of website development and maintenance is reduced.

(3) Allow the author to independently control the display form of all tags in the document.

3.1.2 How to use CSS

CSS styles can be divided into different types according to where they appear. According to this standard, there are mainly three types of styles in CSS:

(1) Inline style, also known as inline style or element-level style. It is used to set specific style rules for an element. It writes specific style rules in the start tag of the element, and the scope of the inline style is limited to this element.

(2) Internal styles, also known as document-level styles or page-level styles. It lists all style rules in the head of the HTML web document, that is, it is written in <style> and </style> (between <head> and </head>), and its scope of action is the entire document.

(3) External styles, also called out-of-line or item-level styles. It writes all style rules in a document (. css file) independent of the web page. It can be used by all necessary HTML web documents in the entire project.

CSS styles must be introduced into HTML documents to be recognized by browsers and applied to HTML elements. Different types of CSS require different import methods. Therefore, there are three ways to introduce the CSS style into the HTML document, which are illustrated with examples below.

(1) Inline style introduction

The CSS style is introduced by directly setting the label attribute style, that is, the declaration block of the style rule is directly used as the attribute value of the style. For example:

    <h2 style="color:red;font-style:italic;">

          welcome

    </h2>

The above method sets the title text to red slanted font.

(2) Import of internal styles

CSS styles are introduced through the <style> tag, which usually needs to be nested in the <head> tag, for example:

        <style type="text/css">

                /* Inline styles go here */

            h2 {color:red;font-style:italic;}

        </style>

This type of style will make all the text defined by the <h2> tag in the web page be in red italic font.

(3) External style introduction

Write the CSS style in an independent .css file, and then introduce it into the head of the HTML document (between <head> and </head>) through the <link> tag. For example:

    <link rel="stylesheet" type="text/css" href="mystyles.css">

In addition, you can also use a special command @import (at rule) between the <style> tags in the <head> head to import files (but not commonly used), such as:

    <style type="text/css">

        @import url(http://www.abc.com/styles.css); 或

        @import "http://www.abc.com/styles.css";

          </style>

3.1.3 Basic concepts of CSS

1. Unit

In page layout, attributes such as width, height, font size, and position of elements are often set. These attribute values ​​exist in a numerical form, and we need to have corresponding units for expression. There are many units in CSS, we only introduce the following ones.

(1) px (pixel)

As everyone is familiar with, the screen is composed of countless grid-like points, and these points are called pixels. For example, 1366 * 768 means that the screen is composed of 1366 pixels in the horizontal direction and 768 pixels in the vertical direction. for example:

(2) % (percentage)

A percentage is a size relative to an element's size (usually the parent element).

(3) em (font size)

em is a relative unit, equal to the font size of the current element.

2. Color value

Usually, a web page is composed of HTML elements of different colors, and CSS provides multiple methods to set the color values ​​of elements.

(1) Keyword

Keywords are composed of English words representing colors, such as red, green, blue, etc. For example:

(2) Hexadecimal value

The hexadecimal value is composed of a 6-bit hexadecimal value and the symbol "#", such as #FFFFFF, #F2F2F2, etc. For example:

(3) Three primary colors (RGB value)

The three primary colors (RGB values) are composed of Red (red), Green (green), and Blue (blue), such as rgb(120, 120, 120), and the three parameters represent the red value, green value, and blue value respectively. The value range is 0~255, and it can also be 3 percentages, such as rgb(10%, 20%, 50%). Combining different values ​​will result in different colors. For example:

3. Inheritance

Inheritance means that when CSS properties are set for a parent element, these CSS properties will also be applied to its child elements, for example, the CSS property "color:red;font-size:24px;" set for the parent element <p> , which also applies to its child elements.

Note: Not all CSS properties will be inherited, and inheritance applies to all nested tag scenarios.

4. Cascading

Style cascading occurs when the same HTML element is defined by more than one style. That is, if multiple CSS styles with the same weight are set for the same element in the HTML file, the last CSS style will be applied. The sample code is as follows:

<style>

     p{color:red;}

     p{color:green;}

</style>

/*The following paragraph text will be displayed in green*/

<p>Xiaohong is a timid girl. </p>

5. Importance

Adding "!important" after a style declaration means that the style has the highest weight and emphasizes the importance of the style. "!important" should be written before the semicolon ";" after the statement.

The sample code is as follows:

<style>

     p{color:red !important;}

     p{color:green;}

</style>

/*Due to the setting of importance, the text of the following paragraph is displayed in red*/

<p>Xiaobai is a bold boy. </p>

6. Element type

CSS elements are divided into several commonly used types such as block elements, inline elements, and inline block elements. Depending on the type of element, the way it is represented in the document varies.

(1) The block element is a standard box, which can be set for any component of the box, and it occupies one line by default.

Common block elements: body, h1~h6, p, ul, ol, li, dl, dt, dd, table, form, div, etc.

(2) The inline element is a non-standard box, setting the width, height, vertical inner margin, and vertical outer margin is invalid, and it shares a line with adjacent elements.

Common inline elements: a, b, s, i, span, etc.

(3) Inline block elements are a combination of block elements and inline elements, which can be set for any component of the box and share a line with adjacent elements.

Common inline block elements: img, input, select, etc.

In CSS, the conversion of element types can be realized through the display attribute. For example:

7. Document flow

The so-called document flow refers to the default arrangement of elements in the document. In normal document flow, the arrangement of elements in a web page is as follows:

(1) Block elements: arranged from top to bottom.

(2) Inline elements: arranged from left to right.

3.3 CSS selectors

In CSS, a selector is a pattern, that is, a pattern used to select the style of an element.

CSS can set the styles of HTML elements separately. For example, set the <p> element to red and the <h1> element to green. The elements can be selected and filtered through CSS selectors, and then different styles can be set.

According to the function of the selector, the selectors in CSS are divided into many (40+) categories, and only a few commonly used ones are introduced below.

1. Selector type

(1) Element selectors are usually HTML elements. In W3C standards, element selectors are also called type selectors. For example:

        <style type="text/css">

                      /*Select the h2 element to apply the following styles*/

                    h2 {color:red; font-style:italic;}

               /*Select the img element to apply the following styles*/

               img {width:200px;}

        </style>

(2) Class selector, the syntax format is ".class selector name", and a dot is used to indicate the class selector. Class selectors allow styling to be specified in a way that is independent of document elements. This selector can be used alone or in combination with other elements. In order to associate a class selector style with an element, class must be specified as an appropriate class selector name. Multiple elements on the same page can use the same class selector name. For example:

    .myfont {color:red; font-style:italic;}

Therefore, the class attribute of multiple different elements can take the value "myfont" to use this style.

(3) ID selectors allow styles to be specified in a way independent of document elements. By setting the ID attribute, and then apply the style according to its attribute value, the syntax format is "#id", and a # sign is used to indicate the ID selector. For example:

    #identifier {color:blue;}

However, the same ID name cannot appear on the same page, because the ID value of an element in a web page is unique. Therefore, only one element in the web page can be styled using ID selectors.

(4) The descendant selector, also known as the containment selector, selects elements according to the nesting relationship between elements. The syntax format is:

    "parents descendant"

Note that ancestor and descendant elements are separated by spaces. For example, the width of an img element (not necessarily a child element) nested in a p element is 120px and can be set as:

    p img {width:120px;}

(5) Sub-selector, selects elements according to the nesting relationship between elements, but only contains sub-elements, the syntax format is:

    "parent>child"

For example:

    p>img {width:120px;} 

It is only valid for the child element img of p, and invalid for descendant elements below the grandson of p.

(6) Intersection selector, use multiple selectors in combination, take the intersection, the syntax format is:

   "p.special"

For example:

    p.special {color:green;}

It is equivalent to adding an element selector restriction to the class selector ".special". The style rules defined by it can only be applied to p elements with class="special" and are invalid for other cases.

(7) Union selector, that is, selector grouping, multiple selectors are used in combination and separated by commas, and the union is taken. The syntax format is:

   "h2, h3, p"

For example:

    p,h2,h3 {color:pink;font-size:16px;}

It is equivalent to setting {color:pink;font-size:16px;} for p, h2, and h3 respectively.

(8) Universal selector, use "*" to represent all elements. For example:

    * {

         padding:0;

         margin:0;

       }

The style it sets will be applied to all elements of the web page.

(9) Anonymous selectors directly introduce CSS styles through the label style attribute, which is the inline style learned earlier. For example:

    <p style="color: red; font-style: italic;">

2. Selector priority

Nine commonly used selectors are introduced in the Selector Types section. So what happens when we apply multiple selectors with the same declaration to the same element? For example, first define the style as:

     p {color:yellow;}

     .special {color:blue;}

Then write the HTML element as:

            <p>As long as you work hard, you can grind an iron pestle into a needle. </p>

            <p class="special">The slowly falling maple leaves are like yearning! </p>

Viewing through the browser, you will find that the content color of the second p element is blue, which is the result of the priority of the selector.

CSS priority means that CSS styles are parsed with different weights in browsers. It is divided into the following situations.

(1) Usually, different selectors are given different priority weights. The inline style (anonymous selector) has the highest weight, which is set to 1000; the weight of the id selector is set to 100; the weight of the class selector is set to 10; the weight of the HTML tag selector is set to 1, CSS select The order of priority of the controllers is shown in the figure below.

(2) If external styles, internal styles, and inline styles are applied to the same element at the same time, it is the case of using multiple styles. Generally, in the case of multiple styles (that is, <link> appears before <style>), the style priority order is as shown in the figure below:

  It should be noted that if the external style introduced by <link> appears after the style declared by <style>, then the external style is equivalent to being defined after <style>, and its priority will be higher than that of the internal style. Therefore, the priority of internal styles and external styles is determined by the order in which they appear in the web page file. When testing, please pay attention to clearing the cache of the browser.

 (3) Setting !important can increase the style priority, for example:

            p {

                color:red !important;

            }

(4) If the above three situations occur at the same time, the order of priority is as follows:

!important >  Anonymous selectors ( inline styles ) > ID selectors > Class selectors > Element (label) selectors >  Universal selectors (*) > Inherited styles 

In this case, what should be done if the priority is the same?

If the CSS priority is the same, the writing order will affect the final execution result, and the later styles will override the previous repeated styles. It can be compared to other programming languages ​​where repeated assignments to variables make it easy to understand the final result. for example:

p {color:red;font-size:20px}

P {color:green;}

Then the paragraph text to which the above style is applied is finally a green font with a size of 20 pixels.

Finally, the precedence rules for each case are summarized as follows:

(1) The larger the weight, the higher the priority;

(2) When the weights are equal, the style sheet setting that appears later is better than the style sheet setting that appears earlier;

(3) The rule of the creator is higher than that of the viewer: that is, the priority of the CSS style set by the web page writer is higher than the default style set by the browser;

(4) The weight of the inherited CSS style is smaller than the later specified CSS style;

(5) Rules marked with "!important" in the same group of property settings have the highest priority.

3.5 CSS Common Properties

1. Font properties

By setting the font, font size, style, and line spacing of the text, the readability of the web page content can be enhanced and the key content can be highlighted.

(1) Set the font size (font-size)

The figure below uses px, %, and em as units to set the font size respectively. When using % and em as units, the font size of the parent element is used as a reference. For example, if the font size of the parent element is 16px, then 62.5% is equivalent to 10px, and 1em is equivalent to 16px.

For example:

Note: The default font size of all browsers is 16px.

(2) Set bold (font-weight)

Set the thickness of the text through the font-weight property. The details of its value are described below.

The value of font-weight is normal, which defines standard characters and is not bold. Normal is the default value.

The value of font-weight is bold, and the text is set to be bold. You can also take the value bolder to set a thicker font; take the value lighter to set a thinner font; take the value inherit to specify the thickness of the font inherited from the parent element.

The value of font-weight is 700, and the value is used to set the text as bold. It can take a value between 100 and 900, and the increment is 100. 400 is equivalent to normal, and 700 is equivalent to bold.

Examples are as follows:

(3) Set the style (font-style)

The value of font-style is normal (the default value), which displays a standard font style.

The value of font-style is italic, and an italic font style will be displayed.

The value of font-style is oblique, and an oblique font style will also be displayed, which is not significantly different from the effect of italic.

The value of font-style is inherit, which stipulates that the font style is inherited from the parent element.

For example:

(4) Set the font (font-family)

You can specify multiple fonts for an element at the same time, and use commas to separate different fonts. If the font name is Chinese characters or consists of multiple words, you must use quotation marks to wrap the font name.

With the font set by the font-family attribute, the browser will read the fonts installed by the system on the user's device. When multiple fonts are specified, the browser will search and set the fonts in order from front to back, as shown in the figure below, if the user computer does not have the "Microsoft Yahei" font installed, it will search for and use the arial font, and so on, until an available font is found. If none of the set fonts is available, the browser default font will be used.

Examples of font settings are as follows:

(5) Set the line spacing (line-height)

Divide the difference between line-height (line spacing or line height) and font-size in half, and add them to the top and bottom of a text line content respectively. The smallest box that can contain these contents is a line box, and the setting of the line-height property will affect the layout of the line box.

For example:

2. Text

Text is one of the core contents of a web page, and it usually involves issues such as text alignment and decoration to highlight the aesthetics of the layout.

(1) Text alignment

Set text alignment Use text-align property, you can set text left alignment, right alignment, center alignment, both ends alignment, etc. For example:

(2) Text modification

Decorated text is set using the text-decoration attribute, which allows setting certain decoration effects on the text, such as underlining, strikethrough, etc. If the descendant element does not have its own decoration, it inherits the settings of the ancestor element.

For example:

3. Positioning

Sets the position of an element relative to an element by positioning coordinates. There are four positioning methods in CSS, namely static positioning, relative positioning, absolute positioning and fixed positioning. CSS uses the position property to set the positioning method. The position of the element is specified by the "left", "top", "right" and "bottom" properties.

(1) Static positioning (static), the default positioning method for all elements, is in the normal document flow. Note that in the static positioning mode, it is meaningless to set the element position coordinates.

For example:

(2) Relative positioning (relative), positioning relative to the original position of the element itself in the web page, will not break away from the document flow.

For example:

(3) Absolute positioning (absolute), generating absolutely positioned elements, positioning relative to the first parent element other than static positioning, will break away from the document flow (meaning that after setting absolute positioning, its original space no longer belongs to the current element).

For example:

(4) Fixed positioning (fixed) also generates absolutely positioned elements, and positioning relative to the browser window will also break away from the document flow.

For example:

4. Link (pseudo-class)

When using hyperlinks, you will find that the text on these links is different from ordinary text in many ways. For example, the text on the link will be underlined, and the color and shape of the mouse will also change.

A hyperlink (<a>) is a very commonly used important label in the web system. It has 4 states: unvisited, visited, hovering and clicking. Different styles can be set according to the different states of the link.

Get the state of the link by:

        a:link not accessed

        a:visited has been visited

        a:hover when hovering

        a:active when clicked

If the styles of the four states are defined at the same time, their writing order needs to be as follows:

   link--visited--hover--active

(i.e. the LoVeHAte principle), otherwise it may fail.

For example:

5. List

Setting the list attribute is mainly used to control the style of the list display, and can be set from several aspects such as the type, position, and picture of the list item mark through several sub-attributes of list-style.

(1) Set the list flag type, use the list-style-type attribute to set, this attribute can take values ​​none (no mark), disc (default, solid circle), circle (hollow circle), square (hollow square) and so on.

For example:

(2) Set the logo type to image, use the list-style-image attribute to set it, and use the image specified by the user to mark the list item.

For example:

(3) Set the position of the logo, using the list-style-position attribute to set it. This attribute can take values ​​inside and outside (default). The difference is that the distance between the mark and the left side of the text content of the list item is different.

For example:

(4) list-style is a composite list property that covers all other list style properties. The above three sub-properties can be written in order with a list-style compound property.

As shown in the following example:

6. Background

You can use different colors, pictures, etc. as the background of the element. When using pictures as the background, it also involves settings such as tiling, position, and scrolling.

(1) Use the background-color attribute to set the background color. The value of this attribute can be a keyword representing the color, a hexadecimal color value, or an RGB color value.

For example:

(2) Use the background-image attribute to set the background image, and the value of this attribute can be given in the form of url (image file location).

For example:

(3) Use the background-position attribute to set the position of the background image. The value of this attribute consists of two parameters. The first parameter indicates horizontal, and the second parameter indicates vertical.

For example:

(4) Set the background tile using the background-repeat attribute. The possible values ​​of this attribute are no-repeat, repeat-x, repeat-y, etc.

For example:

(5) Whether the background image scrolls with the content is set using the background-attachment property, and the possible values ​​of this property are scroll, fixed, etc.

For example:

7. Transparency

Element transparency is particularly obvious when elements are stacked, which means that the clarity of the background can be vaguely seen from the upper elements. To set the transparency of an element, use the opacity (opacity) attribute. The value of this attribute ranges from 0 to 1. 0 means complete transparency, and the larger the value, the more opaque. The setting of transparency can make the element have a certain degree of three-dimensional effect.

For example:

8. Overflow

The nesting of elements produces a parent-child relationship. The outer element is called the parent box, and the inner element is called the child box. When the size of the child box or the plain text content is larger than the parent box, overflow will occur.

The overflow can be handled through the overflow attribute. When the attribute is hidden, the element content is trimmed and the overflow part is invisible; when the attribute is scroll, the element content is trimmed, and the browser displays a scroll bar for the user to browse the overflow part; When the value of this attribute is auto, if the content of the element is trimmed, the browser will display a scroll bar to view the rest of the content.

For example:

9. Hierarchy

When multiple elements are set with overlapping positioning coordinates, they may overlap each other, and their hierarchical order can be adjusted by setting z-index. Taking the plane where the browser is located as the reference plane (that is, z-index=0), the value of the z-axis pointing vertically outward toward the viewer is a positive value, otherwise it is a negative value. A certain degree of three-dimensional effect can also be generated by setting the level.

For example:

10. Floating

Floating can make elements out of the document flow, change the default arrangement of elements, and then flexibly control the layout of the web page. Set the float of the element through the float property.

(1) When the value of float is left, the element is set to float to the left, that is, the element leans to the left.

For example:

(2) When the value of float is right, the element is set to float to the right, that is, the element leans to the right.

For example:

    float:right;

11. Clear floating

To clear the float is to eliminate the influence caused by the float. Use the clear attribute to define which side of the element does not allow floating elements. When the element's clear attribute takes the value left, floating elements are not allowed on the left side of the element; when the element's clear attribute takes the value right, floating elements are not allowed on the right side of the element; when the element's clear attribute takes the value both When , no floating elements are allowed on the left and right sides of the element; when the element's clear attribute has a value of none (the default value), floating elements are allowed on both sides of the element.

For example:

3.6 Box Model

1. The basic concept of the box model

In CSS, in order to conveniently set the CSS properties of elements and realize the corresponding layout, the primary task of the browser is to determine the size of the element.

A basic concept in CSS is the box model. The so-called box model is to regard the elements in the HTML page as a rectangular area, that is, the box of the element.

As shown in the figure below, an element box is composed of four parts: margin (outer margin), border (border), padding (inner margin), and content (content area).

The CSS properties corresponding to these four parts are:

(1) The content area, that is, the area that actually contains the content of the element, which is set through the width and height attributes.

(2) Inner margin, that is, the blank area between the content and the border, which is set through the padding property, and the inner margin in 4 directions can be set separately.

(3) The border refers to the border of the element, which is set through the border attribute, and the borders in 4 directions can be set respectively.

(4) Outer margin, that is, the blank area between adjacent boxes, which is set through the margin attribute, and the outer margins in 4 directions can also be set separately.

Under the standard box model (that is, the value of box-sizing is border-content), the calculation formula of the actual size of the box is as follows:

    The actual size of the box = content + padding + border + margin

In CSS3, if the box-sizing value is border-box, the actual size of the entire box is the set width and height, then the width of the content = width - (padding-left + padding-right) - (border-left + border-right), the height of the content=height - (padding-top + padding-bottom) - (border-top + body-bottom).

There is also the IE box model, but only in IE6 and IE quirks mode.

2. Multi-box margin merge problem

Web pages are arranged in boxes made of multiple elements. Margins will merge between multiple boxes, as follows:

(1) The vertical margins of the upper and lower adjacent block elements are merged. If the upper element has a lower margin and the lower element has an upper margin, the vertical margin is the larger of the two. As shown below.

  (2) The vertical margins of nested block-level elements are merged. If the parent element has no top padding and border, the top margins of the parent element and child elements are merged into the larger one.

4.1 Introduction to JavaScript

1. JavaScript concept

JavaScript is an object-based (Object-based) and event-driven (Event Driven) scripting language with security features. The so-called scripting language is a language that can be mixed with the HTML language. JavaScript realizes a real-time, dynamic and interactive expression ability, and can program the behavior of web pages.

  For example, the case code for popping up a dialog box while opening a page is as follows (demo1.html):

        <html>

          <head>

              <title>First JavaScript Example</title>

              <Script Language="JavaScript">

                  <!-- // Pop up a prompt box

               alert("Welcome to the amazing world of JavaScript!");             

                  -->

              </Script>

          </head>

        </html>

  You can run the above file in your browser to view the results.

2. Features and functions of JavaScript

Its characteristics are:

(1) Dynamic: directly respond to user input, using event-driven approach.

(2) Cross-platform: It is only related to the browser and has nothing to do with the operating environment.

(3) Simplicity: interpreted scripting language, simple basic structure and development process.

Its functions are:

(1) Realize webpage special effects. Including advertising code, navigation menu code, calendar control, floating special effects, text special effects, color special effects and picture special effects, etc.

(2) Realize the front-end verification of form data. For example, verify the data type of a data field in the form or the rules that should be satisfied through JS regular expressions.

(3) Window dynamic operation. For example, realize pop-up windows, element movement, window data transfer, etc.

3. JavaScript code embedding

By analogy with embedding CSS styles in web pages, there are three ways to embed JavaScript code in web pages.

(1) Tag-level embedding, that is, writing JavaScript code directly in HTML tag attribute values.

For example, to test JavaScript's response to button events, write the following code in the web page:

        <button type="button" οnclick="alert('Welcome!')"> Click me!

        </button>

Run the webpage in the browser and click the button, a prompt box with "Welcome!" message will pop up.

(2) Page-level embedding method, that is, embedding JavaScript code into <script>…</script> tags. Usually the JavaScript code is written between the pair of tags in the form of a function, so that the developer can call it where needed in the web page.

For example, to output "HelloWord" on the console, write the following code in the web page:

    <script>

       function hello(){  console.log("Hello World");  }

       hello();

    </script>

Run the webpage in the browser, switch to the console, and you can observe the output of "HelloWord".

(3) External link: project-level import method, that is, load external JavaScript files through <script language="javascript" src="xxx.js">.

For example, put the function part in page-level mode 

   function hello() {  console.log(“Hello World”);  }

Write it in an external file named "hello.js", and then pass it in the head of any webpage that needs to use this function

   <script language=“javascript” src=“hello.js”>

Introduce the js script, and then call it through the following code in the web page. For example:

    <script>

       hello();

    </script>

Run the webpage in the browser, switch to the console, and you can also see the output of "HelloWord".

4.2 JavaScript Basic Syntax

1. Data type

There are 5 primitive data types in JavaScript.

2. Constant

In a programming language, a quantity that has a definite value and can be directly referenced is called a constant. Constants can be classified into: integer constants; floating point constants; Boolean constants; character constants; null values; special characters.

For example:

        <html>

                <head>

                        <title>Use of strings</title>

                        <script language="JavaScript"> 

                             <!--

                             document.write('He said: "JavaScript is very interesting!" '+' is true.');

                             -->

                        </script>

                   </head>

         </html>

3. Variables

In a programming language, a named quantity whose value can be changed and must be declared first and then referenced is called a variable. The following introduces variables from three aspects: naming, type, and declaration.

(1) Variable naming rules

  ◆ The variable name must start with a letter, underscore (_) or dollar sign ($), followed by numbers 0~9, letters A~Z or a~z, underscore (_) or dollar sign ($).

  ◆ Do not use keywords or reserved words in JavaScript as variable names. There are more than 50 keywords or reserved words defined in JavaScript, which are used internally by JavaScript and cannot be used as variable names. Such as var, int, double, true, etc. cannot be used as variable names.

  ◆ JavaScript variable names are case-sensitive. Such as: str and Str represent two different variables respectively.

  ◆ The JavaScript variable name should be able to explain the meaning it represents. For example, str1 and str2 can be used to define two string variables, and sum can be used to sum the variable.

(2) Variable type

  ◆ Integer variables, for example: x=15

  ◆ Real variables, for example: y=22.5

  ◆ Character variable, for example: str="JavaScript"

  ◆ Boolean variables, for example: z=false

(3) Variable declaration

Before JavaScript variables are used, the variable must be declared with the keyword -var, which follows the principle of first explaining and then using.

For example: var sum;

Explanation: Sometimes the variables are used directly without explanation, and there is no error. why?

Tip: Browsers interpret JavaScript as global variables when parsing it.

4. Operators and expressions

(1) Expression

An expression is a formula that combines one data or multiple data using various operation symbols to generate a new value.

For example, 2+2(=4), 2*2(=4), 2+10/2(=7), 4<5(=true).

Expressions are based on operators.

(2) Operators

1) Arithmetic operators

operator

Functional description

type

+

add

binary operator

-

reduce

binary operator

*

take

binary operator

/

remove

binary operator

%

modulo (remainder)

binary operator

++

Increment by 1

unary operator

--

Subtract 1

unary operator

-

reconciliation

unary operator

Examples of self-increment and self-decrement operations:

  Initial Value Expression Calculated Value Description

  x=3 ++x+2 6 x first add 1 and then add

  x=3 --x+2 4 x first subtract 1 and then add

  x=3 x+++2 5 Add first, add 1 to x

  x=3 x--+2 5 Add first, then subtract 1 from x

2) Comparison operators

      operator

     Functional description

        >

       more than the

        <

       less than

       >=

       greater or equal to

       <=

       less than or equal to

       ==

       equal

       != 

       not equal to

Example comparison operators:

        var number1=25;

        var number2=5;

        document.write("number1>number2=");

        document.write(number1>number2);

        document.write("<br>");

        document.write("number1!=number2=");

        document.write(number1!=number2);

Run the above code yourself and observe the results.

3) Logical operators

operator

Functional description

type

&& (logical AND)

Both A and B are true, A&&B is true

binary operator

|| (logical OR)

Both A and B are false, A||B is false

binary operator

! (logical NOT)

false if not true, true if false

unary operator

Examples of logical operators:

    s1=true;

        s2=false;

        document.write("s1&&s2="); 

        document.write(s1&&s2);

        document.write("<br>");

        document.write("s1||s2=");

        document.write(s1||s2);

        document.write("<br>");

        document.write("!s1=");

        document.write(!s1);

        document.write("<br>");

        document.write("!(3==5)||3!=5&&s1=");

        document.write(!(3==5)||3!=5&&s1);

Run the above code yourself and observe the results.

4) String operator (+)

"+" represents the concatenation operation of strings, for example:

   str1="I";

   str2=" like";

   str3=" JavaScript";

   str4=" !";

   document.write("str1+str2+str3+str4= ");

    /* Output: str1+str2+str3+str4= */

   document.write(str1+str2+str3+str4);

    /* Output: I like JavaScript ! */

5) Assignment operator (=)

        x+=y, equivalent to x=x+y;

        x-=y, equivalent to x=xy;

        x*=y, equivalent to x=x*y;

        x/=y, which is equivalent to x=x/y;

        x%=y is equivalent to x=x%y.

    example:

    x=10;

    document.write("x-=10后x=");

    document.write(x-=10);

   Final output: x=0 after x-=10

6) Conditional operator (?:)

The conditional operator (?:) is a ternary operator;

The grammatical format of the conditional operator is: conditional expression? Result 1: Result 2.

It works like this: if the conditional expression evaluates to true, the value of the entire expression is result 1, otherwise the value of the entire expression is result 2.

For example: cj=(score>=60)? "Pass": "Fail";

Meaning: The value in the score variable is greater than or equal to 60, "pass" is assigned to the cj variable, otherwise "failure" is assigned to the cj variable.

7) Object manipulation operators

JavaScript is an object-based programming language, so it contains object manipulation operators such as new, this, and so on.

(1) new operator

Used to define an object instance, the syntax is as follows:

    Object instance name = new object type (parameter);

For example: ma=new Array(3); 

The instance object ma of the Array class is defined.

(2) this operator

this represents the object of the current operation, and it will have different results when used in different places.

Grammar format:

    this.property

    this.method().

4.4 JavaScript commonly used objects

1. The concept of objects

In JavaScript, an object is an instance of a data structure (class) that has properties and methods. Properties are values ​​associated with an object, and methods are actions that an object can perform.

In JavaScript, objects are divided into predefined objects and custom objects. Predefined objects refer to the defined and directly usable objects provided by the system, including built-in objects, document objects , and browser objects .

When calling properties and methods of objects, the most common ways are:

  object.properties

  object.method

JavaScript provides a series of very useful built-in objects, such as Array (array), String (string), Math (numerical calculation), Date (date) and so on.

In order to achieve web page special effects and be able to dynamically control various elements of the web page, it is necessary to understand the browser window and document related objects, including window (window), document (document), history (history), frame (frame), location (address) , form (form) and other objects.

Subsequent chapters will introduce common objects such as window, document, form, and Date.

Objects can also be created in JavaScript. The figure below shows two ways to create objects.

Examples of object calls are as follows (run the observation results by yourself):

<html>

   <head>

     <title>Built-in objects</title>

       <script language="javascript">

         radius=prompt("Please enter the radius of the circle","Please enter the radius of the circle here");

         alert("The circumference of the circle is "+2*Math.PI*radius+", the area of ​​the circle is "+Math.PI*radius*radius);

      </script>

   </head>

</html>

Among them, prompt is a method of the window object, which returns the value entered by the user in the text box.

And call the PI attribute of the Math object, specifically written as Math.PI. 

2. Use of events

The use of event-driven is one of the most basic features of the JavaScript language. The so-called event refers to the operation performed by the user when accessing the page. The commonly used event types are shown in the following table.

The syntax for inserting (calling) an event handler is: on event name = "event handler".

1) Click event: When any element on the page, such as a button, text box or hyperlink, is clicked by the user, a Click event will be generated. For example:

<html>

    <head>

        <title> click事件</title>

    </head>

    <body>

       <form name=button>

         <input type="button" value="上一页"  onClick="history.back()">

         <input type="button" value="新浪网" onClick="location='http://www.sina.com.cn'">

         <input type="button" value="下一页" onClick="history.forward()">

       </form>

    </body>

</html>

2) Dblclick event: When any element on the page is double-clicked by the user, a Dblclick event will be generated.

3) Load event: When the page is loaded, a Load event is generated. For example:

<html>

    <head>

        <title> load事件</title>

    </head>

    <body οnlοad=alert("The web page has been logged in")> </body>

</html>

4) Unload event: When the document in the window is exited, an Unload event is generated.

5) MouseOver event: When the user moves the mouse to a hyperlink or other web page element, a MouseOver event will be generated.

6) MouseOut event: This event is accompanied by the MouseOver event. When the user moves the mouse away from a hyperlink or other web page elements, a MouseOut event will be generated.

<html>

    <head>

        <title> MouseOver and MouseOut events</title>

        <script language="javascript">

            function show() {

                window.status="mouse left"

           }

        </script>

    </head>

    <body>

        <a href="#" onMouseOver=alert("Is the mouse over the text?") onMouseOut=show()>Huaihua College</a>

    </body>

</html>

7) Focus event: When focusing in the text area, a Focus event is generated.

8) Blur event: When the focus is lost in the text area, a Blur event is generated.

For example:

<html>

    <head>

        <title> Focus event and Blur event</title>

    </head>

    <body>

      <form>

            <input type=text value="" onFocus=alert("You can start typing text") onBlur=confirm("Please confirm the input is complete?")

        </form>

</body>

</html>

9) Submit event: When the user clicks the submit button in the form and prepares to submit information to the server, a Submit event will occur. For example:

<html>

    <head>

        <title>submit事件</title>

        <script language="javascript">

            function show() {  

               data=document.form1.text1.value

               if (0<data && data<150)

                    return(true)

               else

                  alert("The value you entered "+data+" is out of range")

            }

        </script>

    </head>

    <body>

       <form name="form1" onSubmit="show()">

            <input type="text" name="text1" value=""><br>

            <input type="submit" value="提交">

       </form>

    </body>

</html>

10) Reset event: When the user clicks the reset button in the form, a reset event is generated.

3. Common objects

1) window object

This object is the window object, which represents the current browser window, and because of its special location, it is the parent of all other browser objects.

Each open browser window corresponds to a window object in the Javascript program. 

The properties of the window object are:

    status: Indicates the status line information of the current browser.

    history: Indicates the history of the current window.

    closed: A logical value indicating whether the current window is closed.

    location: Indicates the information of the current URL displayed in the current window.

    self: Indicates the current window.

The methods of the Window object are:

    Open(URL, window name, window features): Open a new window.

    Close(): Closes a browser window.

    alert(message): pops up an alert dialog box.

    prompt(message, defaultmessage): A prompt dialog box pops up.

    confirm(message): pops up a confirmation dialog box.

    setTimeout(expression, time): After setting a certain period of time, the code represented by expression is automatically executed once, and time is used to set the time in milliseconds.

    setInterval(expression,time,[args]): Set a time interval so that the code represented by expression can be executed periodically. Use time to set the time in milliseconds.

Open or close window cases are as follows:

<html>

    <head>

        <title>Window opening and closing methods</title>

        <script language="javascript">

            function openwindow() {

              window.open("http://www.sina.com.cn","window","width=300, "+ " height=200,status=no,menubar=no");

            }

        </script>

    </head>

    <body οnlοad=openwindow()>

       <form>

          <input type="button" value="Close window" οnclick=window.close()>

        </form>

    </body>

</html>

2) window prompt dialog box

The prompt() method can not only display information like the alert() method and confirm() method, but also provide a text box to ask the user to enter their own information from the keyboard, and it also includes "OK" and "Cancel" buttons.

Its basic syntax format: prompt("prompt information 1","prompt information 2");

Examples of prompt dialog boxes are as follows:

<html>

    <head>

        <title>Use of prompt dialog</title>

        <script language="javascript">

           was hobby, age;

           hobby=prompt("What do you like to do most?");

           alert(hobby);

           age=prompt("How old are you?","Please enter your age here");

           alert(age);

        </script>

    </head>

</html>

3) document object

The document object is a browser object, which represents the document in the browser window, and can be used to process and access HTML elements contained in the document, such as various images, hyperlinks, etc. 

The write() method is the most commonly used method of the document object. 

The properties of the document object are:

    title: Indicates the title of the document.

    bgColor: Indicates the background color of the document.

    fgColor: Indicates the foreground color of the document.

    alinkColor: Indicates the color of the hyperlink when clicked.

    linkColor: Indicates the color of unvisited hyperlinks.

    vlinkColor: Indicates the color of hyperlinks that have been visited.

    URL: Indicates the address of the document.

    lastModified: Indicates the last modification time of the document.

The use case of the document object is as follows:

<html>

    <head>

        <title>Use of document object</title>

        <script language="javascript">

          document.write("The title of the current document: "+document.title +"<br>");

          document.write("The last modification date of the current document: "+

document.lastModified);

        </script>

    </head>

    <body></body>

</html>

4) Date object

The Date object is a built-in object, which provides users with properties and methods for obtaining and setting the date and time, and can be used to help web page creators control the date and time.

To use the Date object, you must use the new operator, the specific syntax format: variable name = new Date ().

The methods of the Date object are:

    getDate(): Returns the date of the current date.

    getDay(): Returns the week (day) number of the current date.

    getMonth(): Returns the month (0-11) of the current date.

    getYear(): Returns the year of the current date.

    getFullyear(): returns the full year.

    getMinutes(): Returns the integer of the minute part of the current time.

    getSeconds(): Returns the seconds of the current time.

    getHours(): Returns the integer of the hour part of the current time.

    getTime(): Returns the current time in milliseconds.

Use cases for the Date object are as follows:

<html>

    <head>

        <script language=JavaScript>      

             today=new Date();      

             year=today.getFullYear();

             month=today.getMonth()+1;

             day=today.getDate();

             theweek=today.getDay();

             switch(theweek) {

              case 0:week="Sunday";break;      

              case 1:week="Monday";break;      

              case 2:week="Tuesday";break;      

              case 3:week="Wednesday";break;      

              case 4:week="Thursday";break;

              case 5:week="Friday";break;      

              case 6:week="Saturday";break; }   

              document.write("<h3>"+"Today is"+year+"year"+month+"month"+day+"day"+week+"</h3>")   

        </script>

    </head>

</html>

5) Form object

The Form object is a form object, which is an important tool for interacting with users through the browser. In the form object, we can add controls such as buttons, text boxes, and lists, and users can put forward their requirements through these controls.

There are two ways to access the form: access the form through "document.form name"; access the form through the array form[#].

The properties of the Form object are:

    name: The name of the form.

    length: The number of elements in the form.

    action: The action performed when the form is submitted, usually the URL of a server-side script.

    elements: represents the array of all control elements in the form, and the subscript of the array is the serial number of the control element in the HTML source file.

    method: HTTP method to send the form.

The methods of the Form object are:

    reset(): Equivalent to the "Reset" button in the form.

    Submit(): Equivalent to the "Submit" button in the form.

The access cases of the Form object are as follows:

<html>

    <head>

        <script language=JavaScript>      

            function clear1(form) {

               form.text1.value="" ;

               form.text2.value="" ;

            }

        </script>

    </head>

    <body>

        <form method=post >

            <input type="text" name="text1"><br>

            <input type="text" name="text2"><br>

            <input type="button" value="清除文字"  οnclick="clear1(this.form)">

    </body>

</html>

5.1 Basics of Responsive Web Design

1. Introduction to Responsive Web

In addition to using traditional large-screen PCs, more and more people use small-screen mobile devices to surf the Internet. Traditional web design is developed for PCs with large screens, and basically has a fixed page size, which is not suitable for browsing on devices with small screens. If the webpage system is designed separately for devices with different screen sizes, the cost is obviously very high. At this time, people hope to have some kind of design technology, once the web page is designed, it can be used everywhere adaptively. Therefore, Responsive Web Design (Responsive Web Design) technology came into being. Responsive web design was proposed by Ethan Marcotte in 2010. He called the combination of media query, grid layout and elastic image as responsive web design.

Responsive web design is compatible with and supported by HTML5+CSS3. The technical points include:

(1) HTML5+CSS3: HTML5+CSS3 adds new tags and attribute content to basic web design.

(2) HTML5 viewport (viewport): Provides attributes for configuring the viewport. In mobile browsers, there are two kinds of viewports, one is the visible viewport (which is what we call the device size), and the other is the window viewport (what is the width of the web page).

(3) CSS3 media queries: identify media types, characteristics (screen width, pixel ratio, etc.).

(4) Flow layout: The effect can be automatically adjusted according to the width of the browser and the size of the screen.

(5) Responsive grid system: rely on media queries to adjust the layout according to different screen sizes.

(6) Streaming image: Scale accordingly with the streaming layout.

2. New features of HTML5

HTML5 is not only the latest version of the HTML specification, it also represents the general term for a series of Web design technologies, the three most important technologies are HTML5 core specification, CSS3 (Cascading Style Sheet, the latest version of Cascading Style Sheet) and JavaScript ( A scripting language used to enhance the dynamic functions of web pages), these three technologies will be involved in later studies. The history of HTML goes back a long way, as discussed in the HTML Basics section. The focus here is on the new feel brought by HTML5.

(1) HTML5 is an evolution rather than a subversion of HTML . Use a browser to open the following URL: W3C HTML5 Logo , you will see the eight innovations of HTML5 on this website.

    1) Semantics: Provides rich semantic tags.

    2) Offline & Storage (Offline & Storage): HTML5 App Cache, LocalStorage, IndexedDB, and File API make Web applications faster and provide the ability to use them offline.

    3) Device Access: Enhanced device awareness enables web applications to be used on computers, pads, and mobile phones.

    4) Communication (Connectivity): Enhanced communication capabilities mean enhanced real-time chat programs and smooth online games.

    5) Multimedia (Multimedia): The enhancement of audio and video capabilities is the biggest breakthrough of HTML5!

    6) Graphics and special effects (3D, Graphics & Effects): Canvas, SVG, WebGL and other functions make graphics rendering more efficient and page effects more cool.

    7) Performance & Integration: WebWorker allows browsers to multithread background tasks without blocking user interface rendering. At the same time, performance testing tools are convenient for evaluating program performance.

    8) Rendering (CSS3): CSS3 can efficiently implement page special effects without affecting the semantics and performance of the page.

(2) Simplify the complicated . Based on the principle of "simple first, simplify as much as possible", HTML5 has made the following improvements:

    1) Simplify DOCTYPE and character set declaration;

    2) Strengthen the HTML5 API to make the page design easier;

    3) Replace complex JavaScript code with the browser's native capabilities;

    4) Precisely defined error recovery mechanism, if there is an error in the page, it will not affect the display of the entire page.

(3) User experience is good . The HTML5 specification takes "customer first" as its purpose. In addition, HTML5 also introduces a new security model to ensure that HTML5 is safe enough. The support of HTML5 by major browsers is constantly improving. Currently, Chrome supports HTML5 the best, and Firefox, Opera, Safari, and IE10 also have good support for HTML5.

3. Basic syntax of HTML5

HTML documents are composed of various tags, and a standard HTML5 template is as follows:

   <!DOCTYPE html> <!-- Located at the front of the document, it is used to explain to the browser the HTML version used by the current document and cannot be omitted. -->

  <html lang="en"> <!-- The lang attribute specifies the language of the element content. -->

<head> <!-- An HTML document can only contain a pair of <head> tags, and most of these parts will not actually be displayed on the page as content. It is mainly used to encapsulate other tags located in the head of the document, such as <title>, <meta>, <link>, etc., to describe the title, author, and relationship with other documents of the document. -->

   <meta charset="UTF-8"> 

   <title>Document</title>

</head>

<body> <!--Used to define the content to be displayed in the HTML document. An HTML document can only contain one pair of <body> tags. -->

   <!--This is a comment--> <!-- The content in this tag is used to explain the code and will not be displayed in the browser. -->

</body>

     </html>

4. HTML5 semantic tags

Compared with traditional web design, one of the major features of HTML5 is to give tags a clearer semantics, which is easier for humans and machines to understand. The commonly used semantic tags in HTML5 are shown in the following table.

tag name

describe

<header> 

Defines the section or page header. 

<section> 

Defines a section (section, section) in a document. Such as chapters, headers, footers, or other parts of the document.

<article> 

Specifies independent self-contained content, such as an article. 

<aside>

Define content outside of page content. is auxiliary information about the content. Can be used as a sidebar for articles.

<figure> 

Specifies individual flow content (images, charts, photos, code, etc.).

<figcaption>

Defines the title of the <figure> tag.

<nav> 

The section that defines the navigation links in the page.

<footer>

Defines the section or page footer.

With semantic structural tags in HTML5, there is a corresponding semantic tag layout, which is compared with the traditional layout as follows:

        Traditional way layout Semantic label layout     

    

5. New features of CSS3

CSS3 is the latest version of CSS, which provides richer and more practical specifications, such as: list modules, hyperlinks, language modules, backgrounds and borders, colors, text effects, multi-column layouts, animations, etc. The use of these specifications It will be explained in turn in the following units. In addition, responsive design is achieved through CSS3 media queries.

(1) Exactly the same as CSS importing HTML files, CSS3 importing HTML documents also has inline style (introduced in the style attribute of the tag), embedded style (introduced in the head of the document using the style tag) and external chain style (introduced in the head through link tag to import .css file) in 3 forms.

(2) Browser private prefix

In order to be better compatible with browsers with different kernels, some properties in CSS3 need to be added with the browser’s private prefix, and a certain style starts with -xx-, as follows:

-webkit- : Only browsers with Webkit as the core can parse it, such as Chrome and Safari.

-moz- : Only browsers with Gecko as the core can parse it, such as Firefox.

-ms- : Only browsers with Trident as the core can parse it, such as IE.

-o- : Only browsers with Presto as the core can parse it, such as Opera.

(3) Commonly used CSS selectors

The function of a CSS selector is to find a specific type of element from an HTML page. Several commonly used CSS selectors are shown in the table below.                

Selector 

  the code

sample code 

illustrate  

universal selector

*

 *{}

Selects all elements.

label selector

element name

a{}、body{}、p{} 

Select elements based on tags.

class selector

.<class name>

. beam {} 

Select elements based on the value of class.

id selector

#<id value>

#logo{} 

Select elements based on the value of id.

attribute selector

[<condition>]

[href]{}、[attr=”val”]{} 

Select elements based on attributes.

union selector

<selector>,<selector>

 em,strong{}

Match multiple selectors at the same time, take the union of multiple selectors.

descendant selector

<选择器> <选择器>

.asideNav li {}

先匹配第二个选择器的元素,并且属于第一个选择器内。

子代选择器

<选择器> > <选择器>

ul>li{}

匹配匹配第二个选择器,且为第一个选择器的元素的后代。

兄弟选择器

<选择器>+<选择器>

p+a{}

匹配紧跟第一个选择器并匹配第二个选择器的元素,如紧跟p元素后的a元素。

伪选择器

: :<伪元素>或: <伪类>

p::first-line{}、a:hover{}

伪选择器不是直接对应HTML中定义的元素,而是向选择器增加特殊的效果。

伪选择器比较特殊,分为伪元素和伪类两种。          

元素名 

 描述 

 :root

 选择文档中的根元素,通常返回html。 

:first-child  

 父元素的第一个子元素。 

:last-child 

 父元素的最后一个子无素。 

:only-child 

 父元素有且只有一个子元素。 

:only-of-type 

 父元素有且只有一个指定类型的元素。 

:nth-child(n) 

 匹配父元素的第n个子元素。 

:nth-last-child(n) 

 匹配父元素的倒数第n个子元素。 

:nth-of-type(n) 

 匹配父元素定义类型的第n个子元素。 

:nth-last-of-type(n) 

 匹配父元素定义类型的倒数n个子元素。 

:link 

 匹配链接元素。 

:visited 

 匹配用户已访问的链接元素。 

:hover 

 匹配处于鼠标悬停状态下的元素。 

:active 

 匹配处于被激活状态下的元素,包括即将点击(按压)。 

:focus 

 匹配处于获得焦点状态下的元素。 

:enabled (:disabled) 

 匹配启用(禁用)状态的元素。 

:checked 

 匹配被选中的单选按钮和复选框的input元素。 

:default 

 匹配默认元素。 

:valid (:invalid) 

 根据输入数据验证,匹配有效(无效)的input元素。 

:in-range (out-of-range) 

 匹配在指定范围之内(之外)受限的input元素。 

(4)浮动与定位

在一个网页中,默认情况下块级元素独占一行,是自上而下排列,行内元素自左向右排列,但是在实际的网页布局中往往需要改变这种单调的排列方式,使网页内容变得丰富多彩,CSS的浮动和定位完美的解决了这个问题。

1)浮动

CSS的浮动可以通过float属性进行设置,默认值为none(不浮动)。

      框1{float:none}            框1{float:right}

  

     框1{float:left}            框1、2、3{float:left}

    

2)定位

在网页开发中,如果需要网页中的某个元素在网页的特定位置出现,例如弹出菜单,这时可以通过CSS的position属性进行设置,示例如下:

        position:relative;       /*相对定位方式*/

        left:30px;               /*距左边线30px*/

        top:10px;                /*距顶部边线10px*/

用于设置菜单定位方式的常用属性值如下表所示。 

描述

static

静态定位(默认定位方式)。

relative

相对定位,相对于其原文档流的位置进行定位。

absolute

绝对定位,相对于 static 定位以外的第一个上级元素进行定位。

fixed

固定定位,相对于浏览器窗口进行定位。

   

用于设置元素具体位置的常用属性值如下表所示。

边偏移属性

描述

top

顶端偏移量,定义元素相对于其参照元素上边线的距离。

bottom

底部偏移量,定义元素相对于其参照元素下边线的距离。

left

左侧偏移量,定义元素相对于其参照元素左边线的距离。

right

右侧偏移量,定义元素相对于其参照元素右边线的距离

3)浮动与定位的使用实例

其实浮动的本意是用来解决图片和文字排版问题的,但是由于它十分好用,被大部分开发者应用到了网页布局,并成为了公认布局的一种方式。    

该图中4个粉色部分使用浮动的知识对页面进行布局,然后使用绝对定位知识创建了一个浮动的div元素。需要注意的是,position: absolute会导致元素脱离文档流,被定位的元素等于在文档中不占据任何位置,在另一个层呈现。float也会导致元素脱离文档流,漂浮在文档流的上层,能遮挡下层元素的空间,但不会遮挡下层元素的内容。

参考代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>浮动和定位</title>
</head>


<body>
    <header class="header">header</header>
    <aside class="aside">aside</aside>
    <section class="main">section</section>
    <footer class="footer">footer</footer>
    <div class="float-div">floatdiv</div>
</body>
</html>

5.2  文本类网页设计

1、HTML5中常用文本标签

文本是网页最常见的主体内容之一,文本类网页设计也是本专业学生必备的基本功之一。HTML5中常用的文本标签如下表所示。

标签

描述

标题标签

HTML中定义了6级标题,分别为h1、h2...h6,每级标题的字体大小依次递减,1级标题字号最大,6级标题字号最小。

段落标签

<p>标签用于定义段落。

<br>标签

<wbr>标签

<br>标签插入1个换行符,用来输入空行,而不是分割段落。

<wbr>规定在文本的何处适合添加换行符。作用是建议浏览器在这个标记处可以断行,不是必定会在此处断行,还要根据整行文字长度而定。除了IE浏览器,其他所有浏览器都支持<wbr>标签。

<details>标签

<summary>标签

<details>标签用于描述文档或文档某个部分的细节,目前只有Chrome浏览器支持<details>标签,可以与<summary>标签配合使用,<summary>标签用于定义这个描述文档的标题。

<bdi>标签

<bdi>标签用于设置一段文本,使其脱离其父标签的文本方向设置。

<ruby>标签

<rt>标签

<rp>标签

<ruby>用于定义ruby注释(中文注音或字符)。与<rt>一同使用。

<rt>标签用于定义字符(中文注音或字符)的解释或发音。

<rp>标签在ruby注释中使用,以定义不支持<ruby>标签的浏览器所显示的内容。

<mark>标签

<mark>标签主要用来在视觉上向用户呈现那些需要突出显示或高亮显示的文字,典型应用是搜索结果中高亮显示搜素关键字。

<time>标签

<time>标签用于定义日期或时间,也可以两者同时。

<meter>标签

<meter>标签用于定义度量衡,仅用于已知最大和最小值的度量

<progress>标签

<progress>标签用于定义任何类型任务的运行进度,可以使用<progress>标签显示JavaScript中时间函数的进程。

2、CSS字体样式属性

CSS的字体样式属性用于定义文本的字体系列、大小、风格等,CSS常用的字体样式属性如下表所示。                               

属性 

允许取值 

描述 

font-size:字号大小 

1em、5em等 

em表示相对于当前对象内文本的字体尺寸。 

5px 

px表示像素,最常用,推荐使用。 

font-family:字体  

"微软雅黑" 

网页中常用的字体有宋体、微软雅黑、黑体等。 

font-weight:字体粗细

normal 

默认值,定义标准的字符。 

bold 

定义粗体字符。 

bolder 

定义更粗的字符。 

lighter 

定义更细的字符。 

100~900(100的整数倍) 

定义由细到粗的字符,其中400等同normal,700等同bold,值越大字体越粗。 

font-style:字体风格 

normal 

默认值,浏览器会显示标准的字体样式。 

italic 

浏览器会显示斜体的字体样式。 

oblique 

浏览器会显示倾斜的字体样式。 

word-wrap:长单词或

URL自动换行

normal 

只在允许的断字点换行(浏览器保持默认处理)。 

break-word 

在长单词或 URL 地址内部进行换行。 

font属性用于对字体样式进行综合设置,字体合写,语法如下所示。

选择器{font:font-style||font-weight||font-size/line-height||font-family;}

                   字体风格     字体粗细    字号大小    行高          字体

3、CSS3的@font-face规则

@font-face是CSS3的新特性,用于定义服务器字体。通过@font-face规则,便可以让用户计算机统一使用服务器安装的字体。

@font-face规则的语法格式如下所示。

        @font-face{

             font-family: <YourWebFontName>;

              src:<source> [<format>][,<source> [<format>]]*;

              [font-weight:<weight>];

             [font-style: <style>];

           } 

YourWebFontName:自定义的字体名称,最好是使用下载的默认字体(下载回来的叫什么字体,这里就填什么字体名)。

source:此值指的是自定义的字体的存放路径,可以是相对路径也可以是绝对路径。

 format:此值指的是自定义的字体的格式,主要用来帮助浏览器识别,其值主要有以下几种类型:truetype、opentype、truetype-aat、embedded-opentype、svg等。

例如(自己运行观察效果):

<!DOCTYPE html>
    <html>
      <head lang="en">
         <meta charset="UTF-8">
         <title>@font-face用法</title>
      </head>
      <style>
        @font-face {
            font-family: myFont;
            src:url('fonts/demo2-1/书法.ttf');
        }
        div{
            font-family: myFont;
            font-size: 4em;
        }
      </style>
    <body>
        <div>
            使用@font-face,应用漂亮的Web字体
        </div>
    </body>
</html>

4、多列布局(Multi-column Layout)

在网页制作中,如果想让一个段落的内容像报刊、杂志中那样分栏显示,就用到了CSS3中提出的多列布局模块(Multi-column Layout Module)。例如(自己运行观察效果):

<!DOCTYPE html>
    <html>
       <head lang="en">
          <meta charset="UTF-8">
          <title>多列布局</title>
       </head>
       <style>
         p{
            width: 1500px;
            /*设置列数*/
            -webkit-column-count: 2;
            /*指定每列固定宽度,列的实际宽度和容器宽度有关*/
            -webkit-column-width: 450px;
            /*设置列与列之间的空隙*/
            -webkit-column-gap: 5em;
            /*设置列中间的分割线,与border的值类似*/
            -webkit-column-rule: 5px solid silver;
            font-size: 27px;
            margin: 0 auto;
         }
       </style>
       <body>
     <p>北京千锋教育科技有限公司是一家专门致力于高素质软件开发人才培养的高科技公司。它依托程序员平台 csdn ,整合了国内众多知名软件企业的资源,并邀请到任跨国公司和国内大中型企业架构师,系统分析师、企业培训师组成自己的团队。前锋教育致力于为企业培养人才的培训理念,以“学员自学入门教程,通过基础考核后进行强化培训”为招生原则,以“针对企业需求,重视基础理论建设,强化高端应用技能”为教学目标,以“高薪保证强大的资深教育团队”为教学后盾,解决所有培训学员的后顾之忧,并解决用人企业难以招聘到合格人才的困扰。</p>
      </body>
   </html>

5、CSS文本外观属性

CSS的文本外观属性用于设置颜色、字间距、字母间距、水平对齐、文本装饰 、阴影等。

属性

描述

允许取值

color 

文本颜色

red, #FF0000,

rgba(0,0,0,0.5)

letter-spacing

字间距

normal, 0.5em, 20px

word-spacing

单词间距

normal, 0.5em, 20px

line-height

行间距

5px, 2em, 150%

text-transform

英文文本转换

none, capitalize,

uppercase, lowercase

text-decoration

文本装饰

none, underline,

overline, line-through

text-align

水平对齐方式

left, right, center

text-indent

首行缩进

10px, 2em, 20%

white-space

空白符处理

normal, pre, nowrap

text-overflow

标示对象内溢出文本

clip, ellipsis

6、添加文本阴影

在CSS中,使用text-shadow属性可以为页面中的文本添加阴影效果,其基本语法格式如下:

     选择器 {text-shadow:h-shadow v-shadow blur color;}

   h-shadow设置水平阴影距离;

   v-shadow设置垂直阴影距离;

   blur设置模糊半径;

   color:设置阴影颜色。

7、Web字体图标

在传统的网页制作过程中,涉及到图标的问题大多用图片进行处理,图片有优势也有不足。例如使用图片会增加总文件的大小和很多额外的“http请求”,增大服务器负担,并且有大量图片下载需要时,增加用户等待时间,牺牲用户体验。另外,图片(位图)在高分辨率屏上会变得模糊,因此,有时候在“响应式设计”中使用图像的最好解决方案就是不去使用图片。而字体通常是矢量的,所以就解决了图片的缺点,即图标字体化。

font-awesome是一个开源免费的字体图标工具,下载后使用步骤如下。

(1)首先去“https://github.com/FortAwesome/Font-Awesome”地址进行下载,下载完毕后解压。

(2)将font字体文件夹和css文件夹以及“font-awesome.min.css”文件拷贝到自己的项目中。

(3)在页面引入font-awesome.min.css文件。

(4)为页面元素添加相应的字体图标class,例如:

       <i class="fa fa-comments">

会在页面显示相应的字体图标。每个图标都有相应的class,如果想使用其他的图标可以去地址:Icons | Font Awesome进行查看。

8、CSS导航栏

对于任何一个网站来说,拥有一个易用的导航栏都是非常重要的,可以大大的提高用户体验,导航栏其实就是一个超链接的列表,所以可以结合使用无序列表<ul>标签和超链接来实现它。可通过运行以下案例来演示导航效果:

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>导航栏</title>
        <style>
             ul{
                list-style-type: none;
                margin: 0;
                padding: 0;
            }
         /*对全站有链接的文字颜色,并立即无下划线*/
             a{color:#333;text-decoration:none; }
         /*对鼠标放到超链接上文字颜色,并文字链接加下划线*/
            a:hover {color: #ff898e;text-decoration:underline;}
            li{
                  float: left;/*li元素浮动的水平导航效果*/
            }
        </style>
      </head>
      <body>
         <ul>
           <li><a href="http://www.baidu.com/">百度</a></li>
           <li><a href="http://www.sina.com/">|新浪</a></li>
           <li><a href="http://www.qfedu.com/">|千锋</a></li>
        </ul>
      </body>
    </html>

5.3  图文类网页设计

1、HTML5常用图像标签

(1)<img>标签:用于定义网页中的图像,语法格式如下所示:

    <img src="图片路径" alt="图片无法显示时显示的文字" />

(2)<figure>标签和<figcaption>标签:当需要在网页中添加一个插图时,就可以使用<figure>标签来实现。例如:

<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>HTML常用的图像标签</title>
      </head>
      <body>
        <figure>
           <p>拍摄者:小菜 拍摄时间:2019 年 4 月</p>
           <img src="images/demo3-1/chicken.png" alt="图片不能显示">
           <figcaption>一只呆萌的小鸡</figcaption>
        </figure>
      </body>
   </html>

2、CSS背景设置

CSS用于背景设置的常用属性详见CSS基础。用backgroung进行背景设置的复合写法语法如下:

    选择器 {

     background: background-color || background-image    || background-repeat ||background-attachment || background-position

   }

如使用该复合属性定义其单个参数,则其他参数的默认值将无条件覆盖各自对应的单个属性设置。默认值为:

         transparent none repeat scroll 0% 0%。

3、盒阴影

使用CSS3的box-shadow属性设置元素阴影。语法如下:

对象选择器 {

       box-shadow: 投影方式||X轴偏移量||Y轴偏移量||阴影模糊半径||阴影扩展半径||阴影颜色

 }

投影方式:此参数是一个可选值,如果不设值,其默认的投影方式是外阴影,设置阴影类型为“inset”时,其投影就是内阴影。

X轴偏移量:是指阴影的水平偏移量,其值也可以是正负值,如果为正值,阴影在对象的右边,反之其值为负值时,阴影在对象的左边。

Y轴偏移量:是指阴影的垂直偏移量,其值也可以是正负值,如果为正值,阴影在对象的底部,反之其值为负值时,阴影在对象的顶部。

阴影模糊半径:此参数是可选,但其值只能是为正值,如果其值为0时,表示阴影不具有模糊效果,其值越大阴影的边缘就越模糊。

阴影扩展半径:此参数可选,其值可以是正负值,如果值为正,则整个阴影都延展扩大,反之值为负值时,则缩小。

阴影颜色:此参数可选,如果不设定任何颜色时,浏览器会取默认色,但各浏览器默认色不一样,特别是在webkit内核下的safari和chrome浏览器将无色,也就是透明,建议不要省略此参数。

阴影举例如下(自行运行观察结果):

<!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>对象阴影</title>
        <link href="images/style.css" rel="stylesheet" type="text/css" />
        <style>
          .box {
             box-shadow:7px 4px 10px #000 inset ;
             width:300px;
             height:80px;
          }
          .box1 img {
             box-shadow:#000 7px 4px 10px ;
          }
        </style>
      </head>
      <body>
        <h3>盒子对象阴影测试</h3>
        <div class="box">DIV盒子内阴影</div>
        <h3>图片对象阴影测试</h3>
        <div class="box1">

        <img src="images/demo3-2/boxshadow.png" />

       </div>
      </body>
    </html>

4、CSS3渐变

渐变分为线性渐变和径向渐变。

线性渐变设置的语法如下:

background-image: linear-gradient([<angle> | <side-or-corner>,]color stop, color stop[, color stop]*);

angle:表示渐变的角度,角度数的取值范围是0~365deg。这个角度是以圆心为起点的角度,并以这个角度为发散方向进行渐变。

side-or-corner:通过关键词来确定渐变的方向。默认值为top(从上向下),取值范围是 [left,right,top,bottom,center,topright,topleft, bottomleft,bottomright,leftcenter,rightcenter]。注意:IE10只能取[left,top],Chrome则没有[center,leftcenter,rightcenter]。

color stop:用于设置颜色边界,color为边界的颜色,stop为该边界的位置,stop的值为像素数值或百分比数值,若为百分比且小于0%或大于100%则表示该边界位于可视区域外。两个color stop之间的区域为颜色过渡区。

线性渐变举例如下(自行运行观察结果):

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>CSS3线性渐变</title>
      </head>
      <style type="text/css">
        .rainbow-linear-gradient{
            width: 460px;
            height: 160px;
            background-image: -webkit-linear-gradient(left,#E50743 0%, #F9870F 15%, #E8ED30 30%, #3FA62E 45%,#3BB4D7 60%,#2F4D9E 75%,#71378A 80%);
        }
      </style>
      <body>
         <div class="rainbow-linear-gradient"></div>
      </body>
    </html>

径向渐变设置的语法为:

background-image:radial-gradient(圆心坐标,渐变形状 渐变大小,

color stop, color stop[, color stop]*);

圆心坐标:用于设置放射的圆形坐标,可设置为形如10px 20px的x-offset y-offset,或使用预设值center(默认值)。

渐变形状:circle:圆形;ellipse:椭圆形,默认值。

渐变大小:

        closest-side或contain:以距离圆心最近的边的距离作为渐变半径。

        closest-corner:以距离圆心最近的角的距离作为渐变半径。

        farthest-side:以距离圆心最远的边的距离作为渐变半径。

        farthest-corner或cove:以距离圆心最远的角的距离作为渐变半径。

重复渐变:对以上两种渐变方式都是适用的,只需在两个属性前添加“ repeating-”,具体语法格式如下:

/*线性重复渐变*/

repeating-linear-gradient(起始角度,color stop, color stop[,color stop]*) 

/*径向重复渐变*/

repeating-radial-gradient(圆心坐标,渐变形状 渐变大小,color stop, color stop[, color stop]*) 

径向渐变举例如下(自行运行观察结果):

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>CSS3径向渐变</title>
        <style type="text/css">
            .rainbow-radial-gradient{
                width: 300px;
                height: 300px;
                background-image: -webkit-radial-gradient(100px, #ffe07b 15%, #ffb151 2%, #16104b 50%);
            }
        </style>
      </head>
      <body>
        <div class="rainbow-radial-gradient"></div>
      </body>
    </html>

5、圆角边框

CSS3的圆角边框实际上是在矩形的四个角分别做内切圆,然后通过设置内切圆的半径来控制圆角的弧度。

CSS3的圆角边框使用border-radius属性来实现,基本语法如下所示:

border-radius: 1-4  length | % / 1-4  length | %;

其中,length或%用于设置对象的圆角形状,不可为负值。如果“/”前后的值都存在,那么“/”前面的值设置其水平半径,“/”后面值设置其垂直半径。如果没有“/”,则表示水平和垂直半径相等。另外其四个值是按照top-left、top-right、bottom-right、bottom-left的顺序来设置。如果省略 bottom-left,则与top-right 相同,如果省略 bottom-right,则与top-left 相同,如果省略top-right,则与top-left 相同。

border-radius是一种缩写的方式,其实border-radius和border属性一样,还可以把各个角单独拆分出来,例如:

border-radius: 2em 1em 4em / 0.5em 3em;

等价于以下四种写法:

border-top-left-radius: 2em 0.5em   //左上角

border-top-right-radius: 1em 3em  //右上角

border-bottom-right-radius: 4em 0.5em  //右下角

border-bottom-left-radius: 1em 3em   //左下角

圆角边框举例如下(自行运行观察结果):

<!DOCTYPE html>
    <html lang="en">
      <head>
         <meta charset="UTF-8">
         <title>CSS3 圆角边框</title>
         <style>
              body {
                   padding: 0;
                   background-color: #F7F7F7;
              }
              div{
                   margin:20px;
                   float: left;
              }
              /*饼环*/
              .border-radius {
                   width: 40px;
                   height: 40px;
                   border: 70px solid #93baff;
                   border-radius: 90px;
              }
              /*四边不同色*/
              .border-radius1 {
                   width: 0px;
                   height: 0px;
                   border-width: 90px;
                   border-style: solid;
                   border-color: #ff898e #93baff #c89386 #ffb151;
              }
         </style>
      </head>
      <body>
         <div class="border-radius"></div>
         <div class="border-radius1"></div>
      </body>
    </html>

6、CSS3过渡

CSS3的过渡就是平滑的改变一个元素的CSS值,使元素从一个样式逐渐过渡到另一个样式。比如,一个块元素从方形逐渐变成圆形。

CSS3过渡使用transition属性来定义,其基本语法如下所示:

transition:property duration timing-function delay;

其中,property:应用过渡的CSS属性的名称;

duration:过渡效果花费的时间;

timing-function:过渡效果的时间曲线;

delay:效果开始之前需要等待的时间。

transition也是一个复合属性,由4个属性构成,如下表所示。

属性

描述

取值

transition-property

规定应用过渡的CSS属性的名称

none, all, property

transition-duration

定义过渡效果花费的时间

time值,秒或毫秒,默认为0表示无效果

transition-timing-function

规定过渡效果的时间曲线

linear, ease, ease-in, ease-out, ease-in-out等

transition-delay

规定效果开始之前需要等待的时间

time值,默认为0

过渡举例如下(自行运行观察效果):

<!DOCTYPE html>
    <html lang="en">
       <head>
         <meta charset="UTF-8">
         <title>CSS3 过渡</title>
         <style>
              /*方环*/
              .border-radius{
                   width: 40px;
                   height: 40px;
                   border: 70px solid #ff6e9b;
                   transition:  3s ;
              }
              /*圆环*/
              .border-radius:hover {
                   width: 40px;
                   height: 40px;
                   border: 70px solid #ff6e9b;
                   border-radius: 90px ;
              }
         </style>
       </head>
       <body>
          <div class="border-radius"></div>
       </body>
    </html>

7、CSS3变形

CSS3动画相关的第二个属性就是transform,翻译成中文的含义是“改变,使…变形;转换”,用于向元素应用2D或3D转换。

形状变换可分为旋转、倾斜、缩放及移动几种类型。

transform属性的基本语法如下所示:

transform:none | transform-functions;

默认值为none,适用于内联元素和块元素,表示不进行变形。

transform-functions用于设置变形函数,可以是一个或多个变形函数列表,2D转换的常用函数说明如下表所示。

属性  

描述  

参数说明  

rotate(angel)  

旋转元素。  

angel是度数值,代表旋转角度。  

skew(x-angel,y-angel)  

倾斜元素。  

angel是度数值,代表倾斜角度。  

skewX(angel)  

沿着  x  轴倾斜元素。  

skewY(angel)  

沿着  y  轴倾斜元素。  

scale(x,y)  

缩放元素,改变元素的高度和宽度。  

代表缩放比例,取值包括正数、负数和小数。  

scaleX(x)  

改变元素的宽度。  

scaleY(y)  

改变元素的高度。  

translate(x,y)  

移动元素对象,基于x和y坐标重新定位元素。  

元素移动的数值,x代表左右方向,y代表上下方向,向左和向上使用负数,反之用正数。  

translateX(x)  

沿着  x  轴移动元素。  

translateY(y)  

沿着  y  轴移动元素。  

matrix(n,n,n,n,n,n)  

2D转换矩阵。  

使用六个值的表示变形,所有变形的本质都是由矩阵完成的。  

元素的变形都有一个原点,元素围绕着这个点进行变形或者旋转,默认的起始位置是元素的中心位置。

CSS 变形使用transform-origin属性指定元素变形基于的原点,语法格式具体如下:

transform-origin: x-axis   y-axis  z-axis;

transform-origin最多接受三个值,分别是x轴(取值为left、center、right、length、%)、y轴(top、center、bottom、length、%)和z轴(length)的偏移量。

注意:transform-origin的三个参数均为可选参数,参数值为0px时可以省略不写。

2D变换案例代码如下(自己运行观察结果):

<!DOCTYPE html>
    <html>
       <head lang="en">
          <meta charset="UTF-8">
          <title>CSS3 2D转换</title>
          <style>
           .demo{
              margin: 25px;
              padding: 0;
              width: 150px;
              height: 50px;
              background-color:  #2bab79;
              font-weight: bold;
              font-size: larger;
              float: left;
           }
           .trans1{
            transform:rotate(30deg);
           }
           .trans2{
            transform:skew(30deg);
           }
           .trans3{
            transform:scale(0.8);
           }
           .trans4{
            transform:translate(5px,50px);
           }

     </style>
      </head>
      <body>
         <div class="demo">不设置变形</div>
         <div class="demo trans1">rotate(30deg)</div>
         <div class="demo trans2">skew(30deg)</div>
         <div class="demo trans3">scale(0.8)</div>
         <div class="demo trans4">translate(5px,50px)</div>
      </body>
   </html>

3D变形是指某个元素围绕其x轴、y轴、z轴进行旋转,transform-functions的常用于3D转换的函数说明如下表所示。

属性  

描述  

参数说明  

rotate3d(x,y,z,angel)  

定义3D旋转。  

前三个值用于判断需要旋转的轴,旋转轴的值设置为1,否则为0,angel代表元素旋转的角度。  

rotateX(angel)  

沿着x轴3D旋转。  

rotateY(angel)  

沿着y轴3D旋转。  

rotateZ(angel)  

沿着z轴3D旋转。  

scale3d(x,y,z)  

定义3D缩放。  

代表缩放比例,取值包括正数、负数和小数。  

scaleX(x)  

沿着x轴缩放。  

scaleY(y)  

沿着y轴缩放。  

scaleZ(z)  

沿着z轴缩放。  

translate3d(x,y,z)  

定义3D转化。  

元素移动的数值。  

translateX(x)  

仅用于x轴的值。  

translateY(y)  

仅用于y轴的值。  

translateY(z)  

仅用于z轴的值。  

matrix3d(n,n,n,n,n,n,

n,n,n,n,n,n,n,n,n,n)

3D转换矩阵。  

使用16个值的 4x4 矩阵。所有变形的本质都是由矩阵完成的  

perspective(n)  

定义3D转换元素的透视视图。  

一个代表透视深度的数值。  

perspective属性的透视效果就是用于实现视觉上的3D效果的,接下来看一个典型的案例——立方体(自己运行观察效果):

<!DOCTYPE html>
    <html lang="en">
       <head>
          <meta charset="UTF-8">
          <title>CSS 3D转换</title>
          <style>
             body {
                margin: 0;
                padding: 0;
                background-color: #F7F7F7;
             }
             .box {
                width: 200px;
                height: 200px;
                text-align: center;
                                line-height: 200px;
                font-size: 24px;
                margin: 100px auto;
                position: relative;
                perspective: 1000px;
                transform-style: preserve-3d;
                transform: rotateX(-30deg) rotateY(30deg);
            }
            .front, .back, .left, .right, .top , .bottom {
                position: absolute;
                width: 100%;
                                height: 100%;
                left: 0;
                top: 0;
                opacity: 0.5;
            }
            .front {
                background-color: pink;
                transform: translateZ(100px);
            }

        .left {
                background-color: green;
                transform: rotateY(90deg) translateZ(-100px);
            }

        .right {
                     background-color: red;
               transform: rotateY(-90deg) translateZ(-100px);
            }

        .top {
               background-color: blue;
               transform: rotateX(90deg) translateZ(100px);
            }

        .bottom {
               background-color: yellow;
               transform: rotateX(-90deg) translateZ(100px);
            }

        .back {
               background-color: purple;
               transform: translateZ(-100px);
                       }
               </style>
    </head>
    <body>
       <div class="box">
           <div class="front">front</div>
           <div class="back">back</div>
           <div class="left">left</div>
           <div class="right">right</div>
           <div class="top">top</div>
           <div class="bottom">bottom</div>
       </div>
     </body>
   </html>

8、CSS3动画

前面学习了CSS3的transition和transform属性,虽然二者结合可以实现一些简单的动画效果,但是也有一些难以克服的缺点,例如我们想让动画在多个状态中转换就无法实现了,CSS3中最后一个动画相关的属性是animations,有了它就可以解决这样的问题。

一个完整的CSS animations由两部分构成:

(1)一组定义的动画关键帧   →   @keyframes规则

(2)描述该动画的CSS声明  →  animation属性

@keyframes规则

在CSS3中使用@keyframes规则来创建动画,keyframes可以设置多个关键帧,每个关键帧表示动画过程中的一个状态,多个关键帧就可以使动画十分绚丽。

@keyframes规则的语法格式如下所示:

@keyframes animationname {

  keyframes-selector{css-styles;}

}

其中,animationname表示当前动画的名称,它将作为引用时的唯一标识,因此不能为空。

keyframes-selector是关键帧选择器,即指定当前关键帧要应用到整个动画过程中的位置值可以是一个百分比、from或者to。其中,from和0%效果相同表示动画的开始,to和100%效果相同表示动画的结束。

css-styles定义执行到当前关键帧时对应的动画状态。以上三个属性都是必需品,缺一不可。

animation属性:

animation属性用于描述动画的CSS声明,包括指定具体动画以及动画时长等行为。

animation属性的基本语法如下所示:

animation:name duration timing-function delay iteration-count direction fill-mode play-state;

与transtion类似,animation也是一个复合属性,以上参数分别对应8个子属性。                            

属性  

描述  

animation-name

规定 @keyframes 动画的名称。

animation-  duration

规定动画完成一个周期所花费时间。

animation-timing-function

规定动画的速度曲线。

animation-delay

规定动画开始前的延迟,可选。

animation-iteration-count

规定动画被播放的次数。

animation-direction

规定动画是否在下一周期逆向播放。

animation-play-state

规定动画是否正在运行或暂停。

animation-fill-mode

规定动画在播放之前或之后,其动画效果是否可见。

动画举例(自行运行观察效果):

<!DOCTYPE html>
    <html lang="en">
       <head>
          <meta charset="UTF-8">
          <title>CSS3 动画</title>
          <style>
             body {
                margin: 0;
                padding: 0;
                background-color: #F7F7F7;
             }
             .box {
                width: 400px;
                margin: 100px auto;
                animation: rotate 4s linear infinite;
             }
             img {
                width: 100%;
                /*display: block;*/
             }
             @keyframes rotate {
               0% {
                  transform: rotateZ(0deg);
               }

           100% {
                   transform: rotateZ(-360deg);
               }
             }
         </style>
      </head>
      <body>
         <div class="box">
            <img src="images/demo3-9/fengche.png">
         </div>
      </body>
   </html>

9、CSS精灵技术

网页开发者以往喜欢把网页里面的图片字节数控制的非常小,往往在一个图片文件夹里散落着很多的小图片,客户端每显示一张图片都会向服务器发送一次请求,图片越多请求次数越多,这样有可能造成图片延迟加载,影响用户体验。随着互联网技术的发展,大家越来越重视网页的加载速度,于是这些小图片被整合到了一起,CSS Sprites出现了。

CSS Sprites被称为CSS精灵技术,是一种网页图片应用处理方式。它允许你将一个页面涉及到的所有小图片都包含到一张大图中去,这样,当访问该页面时,只需要载入一次图片。

CSS精灵技术的使用具体如下:

(1)首先要有一张精灵图,它是许多小图片的合并,由于精灵图要求不高于200KB,所以这种合并适合一般小图标素材。

(2)创建一个容器(如<div>、<i>标签、<span>标签等)来加载精灵图片。

(3)利用CSS的"background-image"、"background-repeat"、"background-position"组合进行背景定位,将一张大图片中的某个部分显示到网页的固定位置。

精灵技术应用举例如下(自行运行观察效果):

<!DOCTYPE html>
    <html>
        <head lang="en">
            <meta charset="UTF-8">
            <title>CSS精灵图</title>
            <style>
               .peach1{
                  position: absolute;
                  top: 50px;
                  left: 0;
                  width:90px;
                  height:100px;
                  background:url(images/peach.png) 0 0 no-repeat;
               }
               .peach2 {
                  position: absolute;
                  top: 70px;
                  left: 100px;
                  width : 90px;
                  height: 100px;                                                      background: url(images/peach.png) 0 -110px no-repeat;
               }
            </style>
        </head>
       <body>
         <span class="peach1" ></span>
         <span class="peach2" ></span>
       </body>
    </html>

5.4  HTML5表单应用

首先需要理解表单的概念,表单是网页上用来收集用户信息的区域,由文本域、复选框、单选框、菜单、文件地址域、按钮等表单元素组成。最常见的表单应用有搜索引擎页面、用户登录页面、用户注册页面等。

<form>标签用于创建一个表单,其基本语法如下所示:

    <form action="url地址"method="提交方式"name="表单名称">

    各种表单控件

</form>

在上面的语法中,name属性用来区分一个网页中的多个表单;action属性用于指定接收并处理表单数据的服务器url地址;method属性用于设置表单数据的提交方式,其取值可以为get或post,默认为get。

简单表单举例:

<!DOCTYPE html>
    <html>
       <head lang="en">
          <meta charset="UTF-8">
          <title>表单</title>
       </head>
       <body>
          <form action="http://www.sina.com/" method="post" >
            <input name="save"/>
            <button>提交按钮</button>
          </form>
        </body>
    </html>

HTML5新增的表单属性:

(1)autocomplete属性

autocomplete属性用于指定表单是否有自动完成功能,所谓“自动完成”是指将表单控件输入的内容记录下来,当再次输入时,会将输入的历史记录显示在一个下拉列表里,以实现自动完成输入。

autocomplete属性有2个值,具体如下:

• true:表单有自动完成功能

• false:表单无自动完成功能

(2)novalidate属性

 novalidate属性用于指定在提交表单时取消对表单进行有效的检查。为表单设置该属性时,可以关闭整个表单的验证,这样可以使form内的所有表单控件不被验证。

演示autocomplete属性的具体应用案例见上例。

HTML5 <input>标签

表单中最为核心的就是<input>标签,使用<input>标签可以在表单中定义文本输入框、单选按钮、复选框、重置按钮等。其基本语法格式如下:

<input type="控件类型" />

在上面语法中,type属性为其最基本的属性,取值有多种,用来指定不同的控件类型,其中email、url、range、number、Date pickers、search、color、tel为新增属性值;除type属性外,还可以定义很多其他属性,常用属性如name、value、size等。

演示<input>标签的具体使用的案例如下:

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>常用表单控件</title>
      </head>
      <body>
        <form action="#" method="post">
            <!--text单行文本输入框-->
            用户名:<input type="text" value="张三" maxlength="6">                      <br><br><!--password密码输入框-->

        密码 :<input type="password" size="40"><br/><br/>
            <!--radio单选按钮-->
            性别:<input type="radio" name="sex" checked/>男
            <input type="radio" name="sex"/> 女<br/><br/>
            <!--number数值输入域-->
            年龄:<input type=number min="18" max="100"><br/><br/>
            <!--checkbox复选框-->
            习惯:<input type="checkbox" />常通风
            <input type="checkbox" />勤洗手
            <input type="checkbox" />戴口罩<br/><br />

        <input type="checkbox" />少聚集<br/><br />

        颜色:<input type="color" value="#ff0000"/><br/><br/>
            <!--file文件域-->
            上传头像:<input type="file" /><br/><br />
            <!--专门用于搜索关键词的文本框-->
            关键词:<input type="search"/><br/><br />
            <!--一定范围内的数值输入域-->
            难易程度: <input type="range" min="1" max="120" /><br/>
            <!--button普通按钮-->
            <input type="button" value="普通按钮"/>
            <!--submit提交按钮-->
            <input type="submit" value="提交"/>
            <!--reset重置按钮-->
            <input type="reset"  value="重置"/>
         </form>
       </body>

 </html>

其它表单标签

除了<input>标签外,HTML还有其他常用表单标签例如<textarea>、<label>、<select>标签等,HTML5之后还增加了<datalist>、<keygen>、<output>表单标签,接下来一一对它们进行介绍。

<textarea>标签用于定义多行文本输入框,可以通过cols和rows属性来规定文本区域内可见的列数和行数,具体的尺寸可以通过width和height来设置。

<textarea rows=""cols="">这里是文本</textarea>

<textarea>标签的常用属性如下表所示:

属性  

允许取值  

取值说明  

name  

由用户自定义  

控件的名称  

readonly  

readonly  

该控件内容为只读(不能编辑修改)  

disabled  

disabled  

第一次加载页面时禁用该控件(显示为灰色)  

maxlength  

正整数  

控件允许输入的最多字符数  

autofocus  

autofocus  

指定页面加载后是否自动获取焦点  

placeholder  

字符串  

为input类型的输入框提供一种提示  

required  

required  

规定输入框填写的内容不能为空  

cols  

number  

规定文本区内的可见宽度。  

rows  

number  

规定文本区内的可见行数。  

例如:

<!DOCTYPE html>
    <html>
       <head lang="en">
          <meta charset="UTF-8">
          <title>textarea</title>
       </head>
       <body>
          <h2>多行文本框:</h2>
          <textarea name="content"  cols="20" rows="10">
            可修改或删除的默认文本,不会在用户输入的时候自动删除,
          </textarea>
       </body>
    </html>

<label>标签用于为 <input>标签定义标注(标记),当用户选择该标签时,浏览器就会自动将焦点转到和标签相关的表单控件上。

<label>标签的应用举例如下:

<!DOCTYPEhtml>

<html>

    <head lang="en">

        <meta charset="UTF-8">

        <title>label</title>

    </head>

    <body>

        性别:

        <label for="male" >男</label>

        <input type="radio"name="sex" id="male"/>

        <label for="female">女</label>

        <input type="radio"name="sex" id="female"/>

    </body>

</html>

<label>标签的for属性值应当与相关标签的id属性相同。

<select>标签可创建单选或多选菜单,其语法格式具体如下:

    <select>

       <option value ="1">选项一</option>

       <option value ="2">选项二</option>

       <option value ="3">选项三</option>

       <option value ="3">选项四</option>

    </select>

  <select>标签中的<option>标签用于定义列表中的可用选项。

 <select>标签的常用属性如下表:                     

标签名  

常用属性  

描述  

<select>  

size  

指定下拉菜单的可见选项数(取值为正整数)。  

multiple  

定义multiple=“multiple”时,下拉菜单将具有多项选择的功能,多选方法为,按住Ctrl键选择多项。  

<option>  

selected  

定义selected =“selected ”时,当前项即为默认选中。  

<select>标签应用举例如下:

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>select</title>
      </head>
      <body>
        <!--单选下拉菜单,可设置默认选中项-->
         所在城市(单选):<br />
        <select>
             <option>-请选择-</option>
             <option selected="selected">北京</option>
             <option>上海</option>
             <option>广州</option>
        </select><br /><br />
        <!--多选下拉菜单,可设置可见选项数,默认选中可以设置多个-->
         兴趣爱好(多选):<br />
        <select multiple="multiple" size="4">
             <option>读书</option>
             <option selected="selected">旅行</option>
             <option selected="selected">听音乐</option>
             <option>运动</option>
        </select>
      </body>
    </html>

<datalist>标签用于定义输入域的选项列表,即与<input>标签配合定义<input>标签可能的值。

列表通过<datalist>标签内的<option>标签创建,可以使用<input>标签的list属性引用<datalist>标签的id属性,具体用法如下。

    <input id="url" list="urlList">

    <datalist id="urlList">

        <option value="www.baidu.com">百度</option>

        <option value="www.sina.com">新浪</option>

        <option value="www.hhtc.edu.cn">怀院</option>

    </datalist>

<keygen>标签是密钥对生成器(key-pair generator)。当提交表单时,会生成两个键,一个是私钥,一个公钥。私钥(privatekey)存储于客户端,公钥(publickey)则被发送到服务器。公钥可用于之后验证用户的客户端证书(client certificate)。具体用法如下:

 <!DOCTYPE html>

 <html>

    <head lang="en">

        <meta charset="UTF-8">

        <title>keygen</title>

    </head>

    <body>

        <form action="#" method="get">

            用户名: <input type="text"name="usr_name" />

            加密强度: <keygen name="security"/>

            <input type="submit" />

        </form>

    </body>

 </html>

 HTML5表单验证     

表单验证是一套系统,它为终端用户检测无效的数据并标记这些错误,让Web应用更快的抛出错误,大大的优化了用户体验。

HTML5自带表单验证功能有两种:

(1)通过required属性校验输入框填写内容不能为空,如果为空将弹出提示框,并阻止表单提交。

(2)通过pattern属性规定用于验证input 域的模式(pattern),它接受一个正则表达式。表单提交时这个正则表达式会被用于验证表单内非空的值,如果控件的值不匹配这个正则表达就会弹出提示框,并阻止表单提交。那些type为email或url的输入控件内置相关正则表达式,如果value的值不符合其正则表达式,那表单将通不过验证,无法提交。

表单验证举例如下:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>HTML5表单验证</title>
      </head>
      <body>
        <form action="#" method="get">
           请输入您的邮箱:

        <input type="email" name="formmail" required/><br/><br/>
           请输入个人网址:

        <input type="url" name="user_url" required/><br/><br/>
            <!--pattern属性用于验证输入的内容是否与定义的正则表达式匹配,正则表达式[1-9]d{5}(?!d)代表六位数中国邮编-->

        请输入中国邮编:<input type="text" pattern="[1-9]d{5}(?!d)" name="postcode" required/><br/><br/>
            <input type="submit" value="提交"/>

      </form>
       </body>
    </html>

5.5  HTML5画布

JavaScript是一门简单的脚本语言,是前端开发中一个重要的角色,我们本节要讲的canvas,它就依赖于JavaScript才能完成一系列操作。

1、JavaScript HTML DOM

JavaScript中把一个HTML网页看作一个DOM对象。DOM的全称为文档对象模型(Document Object Model)。当网页被加载时,浏览器会将HTML网页按照DOM模型构造为如下图所示的对象树。利用JavaScript可动态控制网页行为。

                 

通过JavaScript来创建动态的HTML,主要表现在4个方面:

(1)JavaScript能够改变页面中的所有HTML元素。

(2)JavaScript能够改变页面中的所有HTML属性。

(3)JavaScript能够改变页面中的所有CSS样式。

(4)JavaScript能够对页面中的所有事件做出反应。

要想操作HTML元素及其属性,首先应该获得这个元素对象,document对象的常用获取HTML元素对象的方法如下表所示。

方法     

描述  

getElementById()  

返回对拥有指定 id 的第一个对象的引用。  

getElementsByName()  

返回带有指定名称的对象集合。  

getElementsByTagName()  

返回带有指定标签名的对象集合。  

DOM操作可以获取HTML元素的属性和属性值,接下来通过案例来演示上述三个方法的具体应用,代码如下。

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>JavaScript获取HTML元素对象</title>
        <script type="text/javascript">
            function getValue()
            {
                var x=document.getElementById("input1")
                alert("第一个<input>元素的值为"+x.value);
            }
            function getElements()
            {
                var x=document.getElementsByName("input");
                alert("有"+x.length+"个名称为input的元素");
            }
        </script>
      </head>
      <body>
        <input  name="input" value="1" id="input1" οnclick="getValue()"/><br/>

    <input name="input"  value="2"/><br/>
        <input name="input"  value="3" /><br/>
        <input type="button" οnclick="getElements()" value="元素个数"/>
    </body>
  </html>

2、getBoundingClientRect()方法

用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,或者说一个Element元素的坐标,现在已经是一个W3C标准。

该方法返回一个Object对象,该对象有6个属性:top、left、right、bottom、width、height,具体应用代码如下所示。

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>getBoundingClientRect()</title>
      </head>
      <script>
        /* 该方法应用于button的onmousemove事件*/
        function getRect(){

            //获取元素对象
           var obj= document.getElementById("example");

            //获取按钮位置
           var objRect=obj.getBoundingClientRect();

            //当调用该方法时弹出信息
            alert("top:" + objRect.top + ", right:" + objRect.right + ", bottom:" + objRect.bottom + ", left:" + objRect.left);
    }
      </script>
      <body>
        <!--<center></center>表示将标签内所有的内容居中-->
        <center>
            <button id="example" οnmοusemοve="getRect()" >
                返回本按钮距离浏览器左上角的值
            </button>
        </center>
      </body>
    </html>

3、canvas初识

canvas意为画布,现实生活中的画布是用来作画的,HTML5中的canvas与之类似,我们可以称它为“网页中的画布”,有了这个画布便可以轻松的在网页中绘制图形、文字、图片等。

(1)创建画布

HTML5中提供了<canvas>标签,使用<canvas>标签可以在网页中创建一个矩形区域的画布。

    <canvas id="cavsElem" width="400" height="300">

      您的浏览器不支持canvas ← 当浏览器不支持<canvas>标签时显示

    </canvas>

画布本身不具有绘制功能,可以通过脚本语言(一般为JavaScript)操作绘制图形的API进行绘制操作。可以使用getElementById()方法获取画布对象:

 var canvas = document.getElementById('cavsElem');

(2)准备画笔

有了画布之后,要开始作画需要准备一只画笔,这只画笔就是context对象,该对象可以使用JavaScript脚本获得。

var context = canvas.getContext('2d');

(3)坐标和起点

接下来需要设置上下文开始的绘制点,也就是“从哪里开始画”。

 context.moveTo(x,y);

(4)绘制线条

lineTo()方法用于定义从“x,y”的位置绘制一条直线到指定点或上一个线头点。

 context.lineTo(x,y);

(5)路径规划

绘制线条时,确定起点和终点后,便形成了一条绘制路径,若绘制复杂路径,则必须使用路径开始和结束。

 context.beginPath(); /*开始路径*/  

 context.closePath(); /*闭合路径*/

(6)描边和填充 

在canvas图形绘制中,路径只是草稿,真正绘制线必须执行stroke()方法根据路径进行描边,还可以使用fill()方法进行图形的填充。

context.stroke();//描边

context.fill();//填充

canvas绘制图形-基本步骤总结:

    ①创建画布:<canvas></canvas>

    ②准备画笔(获取上下文对象):canvas.getContext('2d');

    ③开始路径规划:context.beginPath();

    ④移动起始点:context.moveTo(x,y);

    ⑤绘制线条(矩形、圆形、图片...):context.lineTo(x,y);

    ⑥闭合路径:context.closePath();

    ⑦绘制描边:context.stroke();

使用canvas绘制图形的案例如下:

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>Canvas绘制三角形</title>
      </head>
      <body>
        <canvas id="cavsElem">
            你的浏览器不支持canvas,请升级浏览器
        </canvas>
        <script>
            //===============基本绘制API====================
            //获得画布
            var canvas = document.getElementById('cavsElem');
            var context = canvas.getContext('2d');  //获得上下文
            //设置标签的属性宽高和边框
            canvas.width = 900;
            canvas.height = 600;
            canvas.style.border="1px solid #000";
            //绘制三角形
            context.beginPath();        //开始路径
            context.moveTo(100,100);    //三角形,左顶点
            context.lineTo(300, 100);   //右顶点
            context.lineTo(300, 300);   //底部的点
            context.closePath();        //结束路径
            context.stroke();           //描边路径
            //context.fill();       //填充
        </script>
      </body>
    </html>

4、canvas绘图API

(1)canvas绘制矩形和清除矩形

canvas中分别使用strokeRect()和fillRect()方法来绘制矩形边框和填充矩形。使用语法如下:

context.strokeRect(x,y,width,height);

context.fillRect(x,y,width,height);

在canvas中还有一个相当于橡皮擦的方法,使用它可以清除矩形内绘制的内容。使用语法如下:

context.clearRect(x,y,width,height);

案例代码片段如下:

<body>
      <canvas id="cavsElem">
         你的浏览器不支持canvas,请升级浏览器
      </canvas>
      <script>
        //===============绘制矩形====================
        //获得画布
        var canvas = document.getElementById('cavsElem');
        var context = canvas.getContext('2d');  //获得上下文
        //设置标签的属性宽高和边框
        canvas.width = 900;
        canvas.height = 600;
        canvas.style.border="1px solid #000";
        //绘制矩形
        context.strokeRect(0,0,200,100);
        context.fillRect(200,200,200,100);

    //清除矩形(可以取消下行注释观察清除的效果)
       //context.clearRect(100,50,200,200);

   </script>
    </body>

(2)canvas绘制圆形

canvas中使用arc()方法来绘制弧形和圆形。

context.arc( x,y,radius,startAngle,endAngle,bAntiClockwise);

其中,x,y:中心点;

radius:半径长度;

startAngle:开始弧度;

endAngle:结束弧度;

bAntiClockwise:是否逆时针。

案例代码片段如下:

<body>
      <canvas id="cavsElem" width='400' height="300">
        你的浏览器不支持canvas,请升级浏览器
      </canvas>
      <script>
        /* 绘制圆形*/
        //获得画布并上下文对象
        var context = document.getElementById('cavsElem').getContext('2d');
        context.beginPath();//开始路径
        context.arc(100,100,100,0,2*Math.PI,true);//绘制圆形,true为逆时针
        context.closePath();//关闭路径
        context.fillStyle = 'green';//设置填充颜色
        context.fill();//填充
        /* 绘制弧形*/
        context.beginPath();//开始路径
        context.strokeStyle = "#fff";//设置描边颜色
        context.lineWidth = 5;//设置线的粗细

    //绘制弧形,false为顺时针
        context.arc(100,150,25,Math.PI/6,5*Math.PI/6,false);
        // context.closePath();
        context.stroke();//描边
      </script>
    </body>

(3)canvas绘制图片

canvas中的绘制图片其实就是把一幅图放在画布上。

//绘制原图

context.drawImage(image,dx,dy)

//缩放绘图

context.drawImage(image, dx, dy,dWidth,dHeight)

//切片绘图

context.drawImage(image ,sx,sy, sWidth,sHeigh ,dx,dy,dWidth,dHeight)

其中,image表示源图;dx,dy表示目标(画布)中的坐标;dWidth,dHeight表示目标的宽和高;sx,sy表示源图中的坐标;sWidth,sHeigh表示源图的宽和高。

案例代码如下:

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>绘制图片</title>
      </head>
      <body>
        <canvas id="cavsElem" width="400" height="300" >
            你的浏览器不支持canvas,请升级浏览器
        </canvas>
        <script type="text/javascript">
            //获得画布
            var canvas=document.getElementById('cavsElem');
            //设置画布边框
            canvas.style.border="1px solid #000";
            //获取上下文
            var context = canvas.getContext('2d');
            //创建图片对象
            var img=new Image();
            //设置图片路径
            img.src="images/demo5-8/draw.jpg";
            //当页面加载完成使用此图片
            img.onload = function(){
                //使用canvas绘制图片
                context.drawImage(img,0,0);
            };
        </script>
      </body>
    </html>

(4)canvas其他方法

canvas中提供的有关图形绘制的方法还有很多,接下来介绍几个项目会涉及到的方法,具体如下:

clip()方法用于从原始画布剪切任意形状和尺寸的区域。

save()方法用来保存画布的绘制状态。

restore()方法用于移除自上一次调用save()方法所添加的任何效果。

使用clip()裁剪图片效果的案例代码如下:

<!DOCTYPE html>
    <html>
      <head lang="en">
        <meta charset="UTF-8">
        <title>clip()剪切任意形状和尺寸区域</title>
      </head>
      <body>
        <canvas id="cavsElem" width="400" height="300" >
            你的浏览器不支持canvas,请升级浏览器
        </canvas>
        <script>
            //获得画布
            var canvas=document.getElementById('cavsElem');
            //设置画布边框
            canvas.style.border="1px solid #000";
            //获取上下文
            var context = canvas.getContext('2d');
            // 剪切矩形区域
            context.rect(50,20,200,120);//(x,y,width,height)
            context.stroke();//描边
            context.clip();
            // 在 clip()之后绘制圆形,只有被剪切区域的内圆形可见
            context.arc(200,100,70,0,2*Math.PI,true);

        //(x,y,半径,开始弧度,结束弧度,true代表逆时针绘制圆形)
            context.fillStyle="pink";
            context.fill();//填充
        </script>
      </body>
    </html>

5.6  音频与视频

1、视频

在HTML5之前,网页擅长处理的是文字和图像数据。直到现在,大多数视频是通过插件(比如 Flash)来显示的。然而,并非所有浏览器都拥有同样的插件。

HTML5提供了展示视频的标准,规定通过<video>元素来包含视频。<video>元素的播放控件,实现了包括播放、暂停、进度和音量控制、全屏等功能,并允许自定义控件的功能和样式。

视频可以理解为一系列连续的图片,<video>元素的使用方法与<img>元素非常相似,具体语法如下所示:

<video src="视频文件路径"  controls="controls">

  您的浏览器不支持video标签

</video>

其中,controls为视频提供播放控件,<video> 与 </video> 之间插入的内容是供不支持 video 元素的浏览器显示的。

<video>元素用于控制视频播放的常用属性如下表所示。

属性 

允许取值 

取值说明 

autoplay 

autoplay 

如果出现该属性,则视频在就绪后马上播放。  

controls 

controls 

如果出现该属性,则向用户显示控件,比如播放按钮。 

height 

pixels 

设置视频播放器的高度。 

loop 

loop 

如果出现该属性,则当媒体文件播放完后再次开始播放。 

preload 

preload 

如果出现该属性,则视频在页面加载时进行加载,并预备播放。如果使用"autoplay",则忽略该属性。 

src 

url 

要播放的视频的URL。 

width 

pixels 

设置视频播放器的宽度。 

视频文件也有不同格式。目前,<video>标签支持三种视频格式,具体如下:

Ogg:带有Theora视频编码和Vorbis音频编码的Ogg文件。

MPEG4:带有H.264视频编码和AAC音频编码的MPEG4文件。

WebM:带有VP8视频编码和Vorbis音频编码的WebM文件。

目前为止没有一种视频格式让所有浏览器都支持,浏览器对以上格式的支持情况如下表:

视频格式

  IE 9

Firefox 4.0  

Opera 10.6

Chrome 6  

Safari 3.0  

Ogg  

支持  

支持  

支持  

MPEG 4

支持 

支持 

支持 

WebM

支持 

支持 

支持 

HTML5中提供了<source>标签,用于为<video>指定多个视频源,即多个不同格式视频文件的路径,语法如下所示:

<video controls>

     <source src="视频文件地址" type="video/格式">

     <source src="视频文件地址" type="video/格式">

      ……

</video>

注意:<source>标签对于音频文件同样适用,只需要把video改成audio即可。

视频标签使用举例:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>video元素</title>
      </head>
      <body>

    //不带控制面板的视频播放器
        <video src="video/movie.mp4"></video><br/><br/>

    <video src="video/movie.mp4" autoplay></video><br/>//自动播放

    //带控制面板的视频播放器
        <video src="video/movie.mp4" controls></video>
      </body>
    </html>

2、HTML DOM Video对象

HTML5为Video对象提供了用于DOM操作的方法和事件,以及Video对象的常用属性。接下来将对这部分内容进行介绍。

(1)Video对象的常用方法

方法

描述

load() 

加载媒体文件,为播放做准备。通常用于播放前的预加载,也会用于重新加载媒体文件。 

play()

播放媒体文件。如果视频没有加载,则加载并播放;如果视频是暂停的,则变为播放。

pause() 

暂停播放媒体文件。

canPlayType()

测试浏览器是否支持指定的媒体类型。

(2)Vidio对象的常用属性

属性

描述

currentSrc 

返回当前视频的URL。 

currentTime 

设置或返回视频中的当前播放位置(以秒计)。 

duration 

返回视频的长度(以秒计)。 

ended 

返回视频的播放是否已结束。 

error 

返回表示视频错误状态的MediaError对象。 

paused 

设置或返回视频是否暂停。 

muted 

设置或返回是否关闭声音。 

volume 

设置或返回视频的音量。 

height 

设置或返回视频的高度值。 

width 

设置或返回视频的宽度值。 

(3)Video对象的常用事件

事件  

描述  

play

当执行方法play()时触发。

playing

正在播放时触发。

pause

当执行了方法pause()时触发。

timeupdate

当播放位置被改变时触发。

ended

当播放结束后停止播放时触发。

waiting

在等待加载下一帧时触发。

演示Video对象中常用方法、属性和事件的具体应用案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>JavaScript操作video对象</title>
      </head>
      <body>
        <video id="myVideo" src="video/myVideo.ogv"></video>
        <!--<br/><br/>-->
        <input  type="button" value="播放/暂停" οnclick="playPause()"/>
      </body>
      <script>
        var myVideo=document.getElementById("myVideo");
        function playPause()
        {
            if (myVideo.paused)
                myVideo.play();
            else
                myVideo.pause();
        }
      </script>
    </html>

3、音频

目前为止在网页中播放音频没有固定的标准,大多数音频是通过插件(比如Flash)来播放的,但并非所有浏览器都有同样的插件,HTML5中提供<audio>标签来定义Web上的声音文件或音频流,它的使用方法与<video>标签基本相同,语法如下:

   <audio src="音频文件路径" controls>

       浏览器不支持audio标签

   </audio>

<audio>标签的常用属性如下表所示。

属性

允许取值

取值说明

autoplay

autoplay

如果出现该属性,则视频在就绪后马上播放。   

controls

controls

如果出现该属性,则向用户显示控件,比如播放按钮。

loop

loop

如果出现该属性,则当媒体文件播放完后再次开始播放。

preload  

preload  

如果出现该属性,则视频在页面加载时进行加载,并预备播放。如果使用"autoplay",则忽略该属性。

src  

url  

要播放的视频的URL。

<audio>标签支持三种音频格式,具体描述如下:

vorbis:是一种类似ACC的免费、开源的音频编码,是用于替代MP3的下一代音频压缩技术。

MP3:是一种音频压缩技术,其全称是动态影像专家压缩标准音频层面3 (Moving Picture Experts Group Audio LayerIII),简称为MP3。它能够大幅度降低音频数据量。

WAV:是录音时用的标准的Windows文件格式,文件的扩展名为.WAV,数据本身的格式为PCM或压缩型,属于无损音乐格式的一种。

浏览器对上述音频格式的支持情况如下:

音频格式

IE 9  

Firefox 4.0  

Opera 10.6  

Chrome 6.0 

Safari 3.0  

Vorbis  

支持  

支持  

支持  

MP3

支持 

支持 

支持 

Wav

支持 

支持 

支持 

多个音频源使用<source>标签来定义,语法如下:

<audio controls>

     <source src="音频文件路径" type="audio/格式">

     <source src="音频文件路径" type="audio/格式">

     您的浏览器不支持audio标签

</audio>

音频播放器的简单使用案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>audio标签的使用</title>
      </head>
      <body>
        <audio  controls>
             <source src="audio/music.mp3" type="audio/mp3">
        </audio>
      </body>
    </html>

4、HTML DOM Audio对象  

(1)Audio对象的常用方法

方法

描述

load() 

加载媒体文件,为播放做准备。通常用于播放前的预加载,也会用于重新加载媒体文件。

play()

播放媒体文件。如果视频没有加载,则加载并播放;如果音频是暂停的,则变为播放。 

pause()

暂停播放媒体文件。

canPlayType() 

测试浏览器是否支持指定的媒体类型。

(2)Audio对象的常用属性

属性  

描述  

currentSrc

返回当前音频的URL。  

currentTime

设置或返回音频中的当前播放位置(以秒计)。  

duration

返回音频的长度(以秒计)。  

ended

返回音频的播放是否已结束。  

error

返回表示音频错误状态的MediaError对象。  

paused

设置或返回音频是否暂停。  

muted

设置或返回是否关闭声音。  

volume

设置或返回音频的音量。  


 (3)Audio对象的常用事件

事件

描述

play

当执行方法play()时触发。

playing

正在播放时触发。

pause

当执行了方法pause()时触发。

timeupdate

当播放位置被改变时触发。

ended

当播放结束后停止播放时触发。

waiting

在等待加载下一帧时触发。

演示audio对象中常用方法、属性和事件的具体应用案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>JavaScript操作audio对象</title>
      </head>
      <script>
        //页面加载完毕后执行
        window.οnlοad=function(){
            //通过标签名获取button按钮
            document.getElementsByTagName("button")[0].οnclick=                function(){
               //通过标签名获取audio对象
                document.getElementsByTagName("audio")[0].load();
                document.getElementsByTagName("audio")[0].play();
            }
        }
      </script>
      <body>
        <audio src="audio/demo6-5/music.mp3"></audio>
        <button>播放音乐</button>
      </body>
    </html>

(4)深入理解audio和video对象

其实<audio>标签和<video>有很大的相似性,Audio对象和Video对象的DOM操作功能都是由HTMLMediaElement对象统一定义的核心功能,Audio对象指的是HTMLAudioElement对象,它完全继承了HTMLMediaElement对象提供的功能,而Video对象指的是HTMLVideoElement对象,在该对象中提供了额外的功能,主要表现在一些额外的属性上,如下表所示。

属性  

描述  

poster

获取或设置poster属性值。

videoHeight

获取视频的原始高度。

videoWidth

获取视频的原始宽度。

height

设置或返回视频的高度值。

width

设置或返回视频的宽度值。

5.7  响应式web设计

1、基础概念

响应式Web设计中有几个非常重要的概念必须掌握,它们也是响应式设计的关键技术。

(1)视口

视口在响应式设计中是一个非常重要的概念。视口这一概念是针对移动端浏览器的,分为两种视口,一种是可见视口即设备大小,另一种是视窗视口即网页宽度。

比如,设备屏幕是414像素的宽度,在浏览器中,414像素的屏幕宽度能够展示1200像素宽度的内容。那么414像素就是可见视口的宽度,而1200像素就是视窗视口的宽度。

HTML5中,<meta>标签可以用于配置视口属性。

<meta name="viewport" content="user-scalable=no, width=device-width,initial-scale=1.0,maximum-scale=1.0">

其中,user-scalable用于设置用户是否可以缩放,默认为yes。

width=device-width,用于设置视窗视口的宽度,这里表示与可见视口宽度相同。

initial-scale=1.0,用于设置初始缩放比例,取值为0~10.0。

maximum-scale=1.0,用于设置最大缩放比例,取值为0~10.0。

除此之外,还可以用height属性设置视窗视口的高度,minimum-scale设置最小缩放比例。

(2)媒体查询

在CSS3规范中,媒体查询可以根据视口宽度、设备方向等差异来改变页面的显示方式。能够在相同的样式表中,使用不同的样式规则来针对不同的媒介。媒体查询由媒体类型和条件表达式组成,语法如下:

@media  screen and (max-width: 960px) {

     /*样式设置*/

}

它表示媒体类型为screen并且屏幕宽度小于等于960px时的样式。内容可以被显示在显示器、纸媒介或者听觉浏览器等媒体类型上。

媒体查询案例代码如下:

<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="user-scalable=no, width=device-width,initial-scale=1.0, maximum-scale=1.0">
        <title>媒体查询</title>
        <style type="text/css">
            body {
                background-color: red;
                }
            @media (min-width: 320px){
                body {
                    background-color: blue;
                 }
            }
            @media (min-width: 414px){
                body {
                    background-color: yellow;
                }
            }
            @media (min-width: 768px){
                body {
                    background-color: grey;
                    }
            }
            @media (min-width: 960px){
                body {
                    background-color: pink;
                    }
            }
        </style>
      </head>
      <body>
      </body>
    </html>

2、响应式设计

在了解了HTML5为响应式Web设计提供的技术手段后,我们再来学习如何使页面内容也能随页面视口的变化而改变的方式。最常见的响应式Web设计方式有3种,即百分比布局、栅格系统和弹性盒布局。

(1)百分比布局

由于媒体查询只能针对某几个特定阶段的视口,在捕捉到下一个视口前,页面的布局是不会变化的,这样会影响页面的显示,同时也无法兼容日益增多的各种设备。所以,想要做出真正灵活的页面,还需要用百分比布局代替固定布局,并且使用媒体查询限制范围。

其实,固定布局(以像素为单位)可以换算为百分比宽度,来实现百分比布局。

    换算公式为:目标元素宽度/父盒子宽度=百分数宽度

比如,当父盒子的宽度为600px时,

aside{width:300px;}  →  aside{width:50%;}

百分比布局的案例如下:

<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>固定布局转换为百分比布局</title>
        <style type="text/css">
            body>*{

            width:980px; height:auto; margin:0 auto; margin-top:10px;
                border:1px solid #000; padding:5px;}
            header{ height:50px;}
            section{ height:300px;}
            footer{ height:30px;}
            section>*{ height:100%; border:1px solid #000; float:left;}
            aside{ width:250px;}
            article{ width:700px; margin-left:10px;}
        </style>
      </head>
      <body>
        <header>头</header>
        <nav>导航</nav>
        <section>
            <aside>侧边栏</aside>
            <article>文章</article>
        </section>
        <footer>页脚</footer>
      </body>
    </html>

(2)栅格系统

在网页制作中,栅格系统(又称网格系统)就是用固定的格子进行网页布局,是一种清晰、工整的设计风格。

栅格系统最早是应用于印刷媒体上,后来被应用于网页布局中,而随着响应式设计的流行,栅格系统开始被赋予了新的意义。

使用栅格系统进行布局可以让网页布局适应不同设备,如下图所示。

              

栅格系统布局案例如下:

<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="user-scalable=no, width=device-width,initial-scale=1.0, maximum-scale=1.0">
        <title>栅格系统布局</title>
      </head>
      <style type="text/css">
        .row{
            width: 100%;
        }
        /*伪元素:after的一个很重要的用法--清除浮动*/
        .row :after{
            clear: left;/*清除左浮动*/
            content: '';
            display: table;/*该元素会作为块级表格来显示*/
        }
        /*CSS3新增[attribute^=value] 选择器,用于匹配属性值以指定值开头的每个元素。*/
        [class^="col"]{
            float: left;
            background-color: #e0e0e0;
        }
        .col1{
            width: 25%;
        }
        .col2{
            width: 50%;
        }
        @media (max-width: 768px) {
            .row{
                width: 100%;
            }
            [class^="col"]{
                float: none;
                width:100%;
            }
        }
      </style>
      <body>
        <div class="row">
            <header>页头</header>
        </div>
        <div class="row">
            <nav class="col1">导航</nav>
            <div class="col2">主要内容</div>
            <aside class="col1">侧边栏</aside>
        </div>
        <div class="row">
            <footer>页尾</footer>
        </div>
      </body>
    </html>

(3)弹性盒布局

说到响应式,就不得不提CSS3中的弹性盒布局了,它可以轻松的创建响应式网页布局,为盒状模型增加灵活性。

弹性盒由容器、子元素和轴组成,如下图所示。

              

弹性盒改进了块模型,既不使用浮动,也不会在弹性盒容器与其内容之间合并外边距,是一种非常灵活的布局方法。

display是一个关键属性,用于指定弹性盒的容器,其值可以为flex;如果为行内元素,值为inline-flex。例如:

<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>弹性盒属性</title>
      </head>
      <style type="text/css">
        .box {
            min-height: 200px;
            display: flex;/*指定弹性盒的容器*/
            /*
            flex-direction: row|row-reverse|column|column-reverse;
            flex-wrap: nowrap|wrap|wrap-reverse;
             */
            flex-flow: row-reverse;/*弹性子元素按横轴方向顺序排列*/
            justify-content: center;/*弹性子元素向行中间位置对齐*/
            align-items: flex-end;/*弹性子元素向垂直于轴的方向上的中间位置对齐*/
            background-color: gray;
        }
        .A,.B,.C {
            background-color: white;
            border:1px solid gray;
        }
        .box div.A {
            order: 1;/*order设置该子元素出现的顺序*/
            flex-grow: 0;/*扩展比率*/
            flex-shrink: 1;/*收缩比率*/
            flex-basis: auto;/*宽度,像素值*/
            align-self: center;/*该子元素在该行的纵轴上居中放置。*/
        }
        .box div.B {
            order: 2;
            flex: 0 1 auto;/*扩展比0、收缩比1和宽度居中的缩写形式*/
            align-self: stretch;
        }
        .box div.C {
            order: 3;
            flex: 0 1 auto;
             align-self: center;
        }
      </style>
      <body>
        <div class="box">
            <div class="A">A</div>
            <div class="B">B</div>
            <div class="C">C</div>
        </div>
      </body>
    </html>

flex-flow是属性flex-direction 和flex-wrap 的简写,用于排列弹性子元素。

flex-direction的取值如下表所示:                   

取值  

描述  

row 

弹性盒子元素按横轴方向顺序排列(从左往右),默认值。

row-reverse  

弹性盒子元素按横轴方向逆序排列。

column  

弹性盒子元素按纵轴方向顺序排列(自顶向下)。

column-reverse  

弹性盒子元素按纵轴方向逆序排列。

flex-wrap的取值如下表所示:               

取值  

描述  

nowrap  

flex容器为单行,该情况下flex子项可能会溢出容器。  

wrap  

flex容器为多行,flex子项溢出的部分会被放置到新行。  

wrap-reverse  

反转 wrap 排列。  

justify-content属性设置子元素如何在当前轴(横轴)方向的对齐方式,其取值如下表所示。

取值  

描述  

flex-start  

弹性盒子元素将向行起始位置对齐。  

flex-end  

弹性盒子元素将向行结束位置对齐。  

center  

弹性盒子元素将向行中间位置对齐。  

space-between  

两端对齐,弹性盒子元素间空间相等。  

space-around  

两端对齐,弹性盒子元素四周空间相等。  

align-items属性用于设置子元素在垂直于轴(纵轴)的方向上的对齐,其取值如下表所示。

取值  

描述  

flex-start  

弹性盒子元素向垂直于轴的方向上的起始位置对齐(顶对齐)。  

flex-end  

弹性盒子元素向垂直于轴的方向上的结束位置对齐(底对齐)。  

center  

弹性盒子元素向垂直于轴的方向上的中间位置对齐(垂直居中对齐)。

baseline  

弹性盒子元素的第一行文字的基线对齐。

stretch  

如果弹性盒子元素未设置高度或设为auto,将占满整个容器的高度。

order属性用于设置子元素出现的顺序。

flex属性是flex-grow(扩展比率),flex-shrink(收缩比率)和flex-basis(宽度,像素值)的缩写,能够设置子元素的伸缩性。

align-self属性能够覆盖容器中的align-items属性,用于设置单独的子元素如何沿着纵轴排列。

其取值有auto|flex-start|flex-end|center|baseline|stretch,每个值的意义与align-items属性的取值类似。

在使用弹性盒布局时,以下属性不起作用:

①弹性容器的每一个子元素变为一个弹性子元素,弹性容器直接包含的文本变为匿名的弹性子元素。

②第2单元中,多列布局中的column-*属性对弹性子元素无效。

③第1单元中,float和clear 对弹性子元素无效。使用float 会导致display 属性计算为block。

④vertical-align属性对弹性子元素的对齐无效。

弹性盒布局案例如下:

<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
        <title>弹性盒布局</title>
        <style>
            body {
                font: 24px Helvetica;
                background: #fff;
            }
            .main {
                min-height: 500px;
                margin: 0px;
                padding: 0px;
                display: flex;/*设置该div为一个弹性盒容器*/
                flex-flow: row;/*子元素按横轴方向顺序排列*/
            }
            .main > article {
                margin: 4px;
                padding: 5px;
                border-radius:7pt;/*pt也是文字大小的单位,1pt=1px*3/4 */
                background: #719DCA;
                flex:3;/*数字也可达到分配宽度的效果,将容器分为5份,占3份*/
                order:2;/*排序为第2个子元素*/
            }
            .main > nav {
                margin: 4px;
                padding: 5px;
                border-radius: 7pt;
                background: #FFBA41;
                flex: 1 ;/*将容器分为5份,占1份*/
                order: 1;/*排序为第1个子元素*/
            }
            .main > aside {
                margin: 4px;
                padding: 5px;
                border-radius: 7pt;
                background: #FFBA41;
                flex: 1 ;/*将容器分为5份,占1份*/
                order: 3;/*排序为第3个子元素*/
            }
            header, footer {
                display: block;
                margin: 4px;
                padding: 5px;
                min-height: 100px;
                border: 2px solid #FFBA41;
                border-radius: 7pt;
                background: #FFF;
            }
            @media all and (max-width: 640px) {/*当屏幕小于640px时*/
                .main {
                    flex-flow: column; /*弹性盒中的子元素按纵轴方向排列*/
                }
                .main > article, .main > nav, .main > aside {
                    order:0; /*将子元素都设置成同一个值,指按自然顺序排列*/
                }
                .main > nav, .main > aside, header, footer {
                    min-height: 50px;
                    max-height: 50px;
                }
            }
         </style>
      </head>
      <body>
        <header>header</header>
        <div class="main">
            <article>article</article>
            <nav>nav</nav>
            <aside>aside</aside>
        </div>
        <footer>footer</footer>

5.8  Bootstrap前端工具

1、Bootstrap简介

Bootstrap是由Twitter(著名的社交网站)推出的前端开源工具包,它基于HTML、CSS、JavaScript等前端技术,2011年8月在GitHub上发布,一经推出颇受欢迎。

Bootstrap中预定义了一套CSS样式,和与样式对应的jQuery(jQuery是一个快速、小巧、功能丰富的JavaScript库)代码,应用时我们只需提供固定的HTML结构,添加Bootstrap中提供的class名称,就可以完成指定效果的实现。

Bootstrap包中包含内容:

(1)基本结构:Bootstrap提供了一个带有网格系统、链接样式、背景的基本结构。

(2)CSS:Bootstrap自带全局的CSS设置、定义基本的HTML元素样式、可扩展的class,以及一个先进的栅格系统。将在Bootstrap CSS部分详细讲解。

(3)布局组件:Bootstrap包含了十几个可重用的组件,用于创建图像、下拉菜单、导航、警告框、弹出框等等。

(4)JavaScript插件:Bootstrap包含了十几个自定义的jQuery插件。可以直接包含所有的插件,也可以逐个包含这些插件。

(5)定制:开发人员可以定制Bootstrap的组件、LESS变量和jQuery插件来得到一套自定义的版本。

Bootstrap的优势:

(1)移动设备优先:自Bootstrap3起移动设备优先的样式贯穿整个库。

(2)浏览器支持:主流浏览器都支持Bootstrap,包括IE、Firefox、chrome、Safari等。

(3)容易上手:要学习Bootstrap,只需读者具备HTML和CSS基础知识。

(4)响应式设计:Bootstrap的响应式CSS能够自适应于台式机、平板电脑和手机的屏幕大小。

(5)良好的代码规范:为开发人员创建接口提供了一个简洁统一的解决方案,减少了测试工作量。使开发人员站在巨人的肩膀上,不重复造轮子。

(6)组件:Bootstrap包含了功能强大的内置组件。

(7)定制:Bootstrap还提供了基于Web的定制。

Bootstrap下载和环境安装:

(1)下载

首先打开浏览器,访问Bootstrap官方网站“Bootstrap · The most popular HTML, CSS, and JS library in the world.”来下载Bootstrap的最新版本。

下载成功后,解压缩ZIP文件,将看到下面的文件和目录结构,如下所示:

这些预编译文件可以直接应用到Web项目中,其中map文件只有在自定义高级开发时会应用到,在实际开发中通常的做法是,整体进行拷贝,所以该部分作为了解即可。

(2)环境安装

以下是使用Botstrap的标准模板。

<!DOCTYPE html>

<html>

    <head>

        <title>Bootstrap模板</title>

        <meta charset="UTF-8">

        <meta name="viewport"content="width=device-width, initial-scale=1.0"> //这2个meta标签须放在最前面,其他内容须跟随其后。

        <link href="css/bootstrap.min.css" rel="stylesheet">

    </head>

    <body>

       <div class="container" style="border:1px solid #000000; height:100px;">.container</div>
           <!--整个宽度-->
           <div class="container-fluid" style="border:1px solid #000000; height:100px;">.container-fluid</div>

        //js文件在需要时必须放在body的最后面引入,否则可能出错!

        <script src="jquery/jquery-1.11.0.min.js"></script>

        <script src="js/bootstrap.min.js"></script>

    </body>

</html>

在使用模板时,要特别注意引入文件的存放路径。

(3)布局容器

使用Bootstrap时需要为页面内容和栅格系统包裹一个.container布局容器。

Bootstrap包中提供了两个容器类,.container类和.container-fluid类。

.container类用于固定宽度并支持响应式布局的容器,用法如下:

<div class="container">

   ...

</div>

.container-fluid类用于设置100%宽度,占据全部视口(viewport)的容器,用法如下:

<div class="container-fluid">

    ...

</div>

注意:由于padding 等属性的原因,这两种容器类不能互相嵌套。

布局容器案例见(2)中案例。

(4)导航栏(navbar)

Bootstrap导航栏是在应用或网站中作为导航页头的响应式基础组件。

Bootstrap中默认样式的导航条在移动设备上可以折叠(并且可开可关),且在视口(viewport)宽度增加时逐渐变为水平展开模式。

缩小浏览器窗口后,菜单均被隐藏,代替出现的是一个汉堡按钮。

单击“汉堡按钮”,显示被隐藏菜单的下拉列表。

使用Bootstrap制作基础导航栏主要分为以下步骤:

①添加一个容器<nav>或<div>标签,使用.navbar类和.navbar-default类,并且添加role="navigation",增加可访问性。

②向<div>标签添加一个标题使用.navbar-header类,内部包含带有.navbar-brand类的<a>标签,用于定义品牌图标,如果是文字视觉上会稍大些。

③为了向导航栏添加链接,只需要简单地添加带有.nav类、.navbar-nav类的无序列表即可。

具体案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <title>Bootstrap基础导航栏</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/bootstrap.min.css" rel="stylesheet">
      </head>
      <body>
        <nav class="navbar navbar-default" role="navigation">
            <!--这里可以定义品牌图标-->
            <div class="navbar-header">
                <a class="navbar-brand " id="nav-brand-itheima"                       href="#" >网站首页
                </a>
            </div>
            <ul class="nav navbar-nav">
                <li class="active"><a href="##">系列教程</a></li>
                <li><a href="##">名师介绍</a></li>
                <li><a href="##">成功案例</a></li>
                <li><a href="##">关于我们</a></li>
            </ul>
         </nav>

     <script src="jquery/jquery-1.11.0.min.js"></script>

     <script src="js/bootstrap.min.js"></script>
      </body>
    </html>

实现响应式

基础导航栏只能适应大屏幕的浏览器,当浏览器窗口缩小到一定程度时,菜单将被折叠。

①实现菜单的折叠和隐藏,把小屏幕时需要折叠的内容包裹在一个<div>标签内,并且为这个<div>标签使用.collapse、.navbar-collapse两个类,最后为这个div添加一个id。

②添加在小屏幕时,要显示的汉堡按钮的固定写法:

    <button class="navbar-toggle" type="button" data-toggle="collapse">

        <span class="sr-only">ToggleNavigation</span>

        <span class="icon-bar"></span>

        <span class="icon-bar"></span>

        <span class="icon-bar"></span>

    </button>

将上述案例的body部分改为以下代码,即可完成菜单隐藏:

 <body>
        <nav class="navbar navbar-default" role="navigation">
           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded= "false">
             <span class="sr-only">汉堡按钮</span>
             <span class="icon-bar"></span>
             <span class="icon-bar"></span>
             <span class="icon-bar"></span>
           </button>
           <!--这里可以定义品牌图标-->
           <div class="navbar-header">
              <a class="navbar-brand " id="nav-brand-itheima" href="#" >网站首页
              </a>
          </div>
          <div class="collapse navbar-collapse" id="navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a href="##">系列教程</a></li>
                <li><a href="##">名师介绍</a></li>
                <li><a href="##">成功案例</a></li>
                <li><a href="##">关于我们</a></li>
            </ul>
          </div>
        </nav>

    <script src="jquery/jquery-1.11.0.min.js"></script>

    <script src="js/bootstrap.min.js"></script>
   </body>

Bootstrap提供的是基础的CSS样式,如果想自定义样式,有两种方式:

①最直接的方式是查找Bootstrap源码样式,用CSS覆盖掉这些默认样式。具体可以通过查看针对Bootstrap中使用的demo使用哪些类名控制我们要修改的样式,然后使用该类名并且编写自己的样式来实现覆盖。

②使用!important提高代码优先级。

例如修改导航条的默认背景色可以通过为.navbar-default类添加样式来实现,在上例中的<head>部分添加如下代码即可:

<style>

  .navbar-default{

       background-color: pink; }

</style>

至此,对Bootstrap有了初步的认识,是否发现有些问题,请思考一下原因。

2、重要控件

(1)表单

几乎所有的网站中都涉及到表单的应用,接下来介绍如何使用Bootstrap创建表单。

Bootstrap通过一些简单的HTML标签和扩展的类即可创建出不同样式的表单,按照布局的不同,主要分为三类:垂直表单(默认)、内联表单和水平表单。

垂直表单也称为基本表单,使用Bootstrap制作基本表单主要分为以下步骤:

①向父<form>标签添加role="form"。

②把标签和控件放在一个类名为form-group的<div>中,获取最佳间距。

③向所有文本标签<input>、<textarea>和<select>添加.form-control类。

在案例页面<body>中添加代码片段如下:

<form role="form">
     <div class="form-group">
        <label for="name">名称</label>
        <input type="text" class="form-control" id="name"
               placeholder="请输入名称">
     </div>
     <div class="form-group">
        <label for="inputfile">文件输入</label>
        <input type="file" id="inputfile">
        <p class="help-block">这里是块级帮助文本的实例。</p>
     </div>
     <div class="checkbox">
        <label>
            <input type="checkbox">记住我
        </label>
     </div>
     <button type="submit" class="btn btn-default">提交</button>
   </form>

Bootstrap创建内联表单,只需要在垂直表单的基础上,为<form>标签添加类.form-inline。例如:

<form role="form" class="form-inline">

水平表单与其他表单不仅标记的数量上不同,而且表单的呈现形式也不同。创建水平布局的表单的步骤具体如下所示:

①向父<form>标签添加类.form-horizontal,改变.form-group的行为,并使用Bootstrap预置的栅格class将label和控件组水平并排布局。

②把标签和控件放在一个带有.form-group类的<div>中。

③向标签添加.control-label类。

在案例页面<body>中添加代码片段如下:

<form class="form-horizontal" role="form">
     <div class="form-group">
        <label for="name" class="col-sm-2 control-label">用户名</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="name" placeholder="请输入用户名">
        </div>
     </div>
     <div class="form-group">
        <label for="password" class="col-sm-2 control-label">密码</label>
        <div class="col-sm-10">
            <input type="password" class="form-control" id="password" placeholder="请输入密码">
        </div>
     </div>
     <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <div class="checkbox">
                <label>
                    <input type="checkbox"> 请记住我
                </label>
            </div>
        </div>
     </div>
     <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default">登录</button>
        </div>
     </div>
</form>

在实际开发中有时需要改变表单的默认尺寸和样式,可以通过如下方式来改变表单控件的尺寸和样式:

①使用.input-lg和.input-sm为控件设置高度。

②通过.col-lg-*为控件设置宽度。

③通过覆盖.form-control的样式来改变控件的样式。

案例代码片段如下:

<style>
      .form-control{
        background: pink;
      }
    </style>
    <body>
      <form class="form-horizontal" role="form">
        <input class="form-control input-lg"type="text"placeholder=".input-lg">
        <input class="form-control" type="text"placeholder="Defaultinput">
        <div class="col-lg-3">
            <input class="form-control input-lg" type="text" placeholder="input-lg col-lg-3"></p>
        </div>
        <input class="form-control input-sm" type="text" placeholder="input-sm"></p>
      </form>
    </body>

(2)按钮

Bootstrap提供了一些类来定义按钮的样式,支持<a>、<button>和<input>标签,具体如下表所示。

类  

描述  

.btn  

为按钮添加基本样式。  

.btn-default  

默认/标准按钮。  

.btn-primary  

原始按钮样式(未被操作)。  

.btn-success  

表示成功的动作。  

.btn-info  

该样式可用于要弹出信息的按钮。  

.btn-warning  

表示需要谨慎操作的按钮。  

.btn-danger  

表示一个危险动作的按钮操作。  

.btn-link  

让按钮看起来像个链接  (仍然保留按钮行为)。  

.btn-lg  

制作一个大按钮。  

.btn-sm  

制作一个小按钮。  

.btn-xs  

制作一个超小按钮。  

.btn-block  

块级按钮(拉伸至父元素100%的宽度)。  

.active  

按钮被点击。  

.disabled  

禁用按钮。  

不同样式按钮的应用案例代码片段:

<body>
    <!-- 标准的按钮 -->
    <button type="button" class="btn btn-default">默认按钮</button>

 <!-- 提供额外的视觉效果,标识一组按钮中的原始动作 -->
    <button type="button" class="btn btn-primary">原始按钮</button>

    <!-- 表示一个成功的或积极的动作 -->
    <button type="button" class="btn btn-success">成功按钮</button>

    <!-- 信息警告消息的上下文按钮 -->
    <button type="button" class="btn btn-info">信息按钮</button>

    <!-- 表示应谨慎采取的动作 -->
    <button type="button" class="btn btn-warning">警告按钮</button>

    <!-- 表示一个危险的或潜在的负面动作 -->
    <button type="button" class="btn btn-danger">危险按钮</button>

    <!-- 并不强调是一个按钮,看起来像一个链接,但同时保持按钮的行为 -->
    <button type="button" class="btn btn-link">链接按钮</button>
    </body>

Bootstrap中提供了一些类用于控制按钮的大小,如下表所示。

类  

描述  

.btn-lg  

 大按钮。  

.btn-sm  

小按钮。  

.btn-xs  

超小按钮。  

.btn-block  

创建块级的按钮,会横跨父元素的全部宽度。  

3、栅格系统

Bootstrap提供了一套响应式、移动设备优先的流式栅格系统,随着屏幕或视口(viewport)尺寸的增加,系统会自动分为最多12列。它包含了易于使用的预定义类,和强大的mixin用于生成更具语义的布局。

栅格系统用于通过一系列的行(row)与列(column)的组合来创建页面布局,开发者可以将内容放入这些创建好的布局中。其工作原理如下:

①“行”必须包含在布局容器.container类或.container-fluid类中,以便为其赋予合适的排列(aligment)和内补(padding)。

②通过行(row)在水平方向创建一组列(column),并且只有列(column)可以作为行(row)的直接子元素。

③行使用的样式.row,列使用样式col-*-*,我们的内容应当放置于列(column)内,列大于12时,将另起一行排列。

④Bootstrap栅格系统为不同屏幕宽度定义了不同的类。

Bootstrap3使用了4种栅格选项来形成栅格系统,栅格选项的类前缀的取值分别是col-xs、col-sm、col-md、col-lg,其中,lg是large(大)的缩写,md是mid(中等)的缩写,sm是small(小)的缩写,xs是extrasmall(超小)的缩写。例如使用.col-xs适用于小于768px的超小屏幕。这4种栅格选项的区别在于适合不同尺寸的屏幕设备,可在官网上查看更加具体的介绍。

栅格系统可以让用户在不同尺寸的设备上看见不同的布局效果,演示栅格系统具体应用的案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <title>栅格系统</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/bootstrap.min.css" rel="stylesheet">
      </head>
      <body>
        <style>
            div{
                border: 1.5px solid #000000;
            }
        </style>
        <br>
        <div class="container">
            <div class="row">
                <div class="col-md-3 col-xs-6">1</div>
                <div class="col-md-3 col-xs-6">2</div>
                <div class="col-md-3 col-xs-6">3</div>
                <div class="col-md-3 col-xs-6">4</div>
            </div>
            <div class="row">
                <div class="col-md-3 col-xs-6">5</div>
                <div class="col-md-3 col-xs-6">6</div>
                <div class="col-md-3 col-xs-6">7</div>
                <div class="col-md-3 col-xs-6">8</div>
            </div>
        </div>
        <script src="js/bootstrap.min.js"></script>
      </body>
    </html>

4、标签页

Bootstrap提供了几种标签页,这里只讲解一下应用比较广泛的胶囊标签页。Bootstrap制作胶囊标签页主要分为以下步骤:

①使用一个完整的标签页分为页头选项卡和内容两部分。

②页头使用<ul>标签,在<ul>中添加.nav和.nav-tabs类,会应用Bootstrap标签页样式;添加.nav和.nav-pills类会应用胶囊标签样式。需要几个标签项就添加几个<li>标签。

③在<li>标签中添加<a>标签,<a>标签的href的值直接跟标签页下面的内容<div>的id关联,十分重要。

④在<a>标签中添加data-toggle="tab"或data-toggle="pill"。页头部分示例代码如下所示。

 <ul class="nav nav-tabs">

     <li><a href="#identifier" data-toggle="tab">Home</a></li>

      ...

 </ul>

⑤内容部分最外层使用<div>标签添加类.tab-content,然后添加每个标签项对应的<div>标签,这些标签添加类.tab-pane和对应标签项的id值,示例代码如下所示。

<div class="tab-content">

     <div class="tab-pane active" id="home">...</div>

     <div class="tab-pane " id="profile">...</div>

     <div class="tab-pane " id="messages">...</div>

</div>

注意:④中代码的红色identifier对应⑤中代码的红色id值home、profile、messages等。

演示最基本的胶囊标签页的案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <title>胶囊标签页</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/bootstrap.min.css" rel="stylesheet">
      </head>
      <body>
        <br>
        <ul class="nav nav-pills">
            <li role="presentation" class="active"><a href="#home" role="tab" data-toggle="pill">Home</a></li>
            <li role="presentation"><a href="#profile" role="tab" data-toggle="pill">Profile</a></li>
            <li role="presentation"><a href="#messages" role="tab" data-toggle="pill">Messages</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane active" id="home">我是第一页</div>
            <div class="tab-pane" id="profile">我是第二页</div>
            <div class="tab-pane" id="messages">我是第三页</div>
         </div>
        <script src="jquery/jquery-1.11.0.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
      </body>
    </html>

5、响应式工具

Bootstrap提供了一套辅助工具类,使用这些工具类可以通过媒体查询结合大型、小型和中型设备,实现内容在设备上的显示和隐藏,目前只适用于块级元素和表格的切换。

超小屏幕  手机 (<768px)  

小屏幕 平板 (≥768px)  

中等屏幕 桌面 (≥992px)  

.visible-xs-* 

可见 

隐藏 

隐藏 

.visible-sm-* 

隐藏 

可见 

隐藏 

.visible-md-* 

隐藏 

隐藏 

可见 

.visible-lg-* 

隐藏 

隐藏 

隐藏 

.hidden-xs 

隐藏 

可见 

可见 

.hidden-sm 

可见 

隐藏 

可见 

.hidden-md 

可见 

可见 

隐藏 

.hidden-lg

可见

可见

可见

演示案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <title>响应式工具</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <style>
            div{
                border: 1px solid black;
                font-weight: 800;
            }
        </style>
      </head>
      <body>
        <br>
        <div class="container" style="padding: 40px;">
            <div class="row visible-on">
               <div class="col-xs-6 col-sm-3" >
                 <span class="hidden-xs">特别小型设备隐藏</span>
                 <span class="visible-xs">在特小型设备上可见</span>
               </div>
               <div class="col-xs-6 col-sm-3" >
                   <span class="hidden-sm">小型设备隐藏</span>
                   <span class="visible-sm">在小型设备上可见</span>
               </div>
               <div class="clearfix visible-xs"></div>
               <div class="col-xs-6 col-sm-3" >
                   <span class="hidden-md">中型设备隐藏</span>
                   <span class="visible-md">在中型设备上可见</span>
               </div>
               <div class="col-xs-6 col-sm-3" >
                   <span class="hidden-lg">大型设备隐藏</span>
                   <span class="visible-lg">在大型设备上可见</span>
               </div>
            </div>
        </div>
      </body>
    </html>

6、轮播插件

Bootstrap轮播(Carousel)插件是一种灵活的响应式的向站点添加滑块的方式。轮播的内容可以是图像、内嵌框架、视频或者其他想要放置的任何类型的内容,使用该插件时必须引入bootstrap.js或压缩版的bootstrap.min.js。

轮播图的实现主要由三个部分构成:轮播的图片、轮播图片的计数器、轮播图片的控制器。

(1)设计轮播容器

使用.carousel类设计轮播图片的容器,并为该容器添加id,方便后面的使用,示例代码如下所示。

<div id="slidershow">

     ...

</div>

(2)设计轮播计数器

在轮播容器div.carousel的内部添加轮播计算器.carousel-indicators类,其主要功能是显示当前图片的播放顺序(有几张图片就放置几个li),一般采用有序列表来制作,该内容放在轮播容器内,示例代码如下所示。

 <!--设置图片轮播的顺序-->

 <ol class="carousel-indicators">

     <li class="active">1</li>

     <li>2</li>

     <li>3</li>

     <li>4</li>

     <li>5</li><

  </ol>

(3)设计轮播图片控制器

在Carousel中通过.carousel-control类配合left和right来实现轮播控制器。其中left表示向前播放,right表示向后播放。该内容同样放在carousel轮播容器内,示例代码如下所示。

<!--设置轮播图片控制器-->

<a class="left carousel-control" href="" >

    <span class="glyphicon glyphicon-chevron-left"></span>

</a>

<a class="right carousel-control" href="">

    <span class="glyphicon glyphicon-chevron-right"></span>

</a>

(4)添加图片描述

Bootstrap中可以使用<div>标签添加.carousel-caption类为图片添加描述信息,这部分内容只需要在div.item中图片底部添加对应的代码,示例代码如下所示。

<!--图片对应标题和描述内容-->

<div class="carousel-caption">

     <h3>图片标题</h3>

     <p>描述内容...</p>

</div>

(5)声明式触发轮播

声明式方法是通过定义 data属性来实现,data 属性可以很容易地控制轮播的位置。主要包括以下几种:

①data-ride属性:取值carousel,并且将其定义在carousel上。

②data-target属性:取值carousel定义的ID名或者其他样式识别符,如前面示例所示,取值为“#slidershow”,并且将其定义在轮播图计数器的每个<li>标签上。

③data-slide属性:取值有两个,prev表示向后滚动,next表示向前滚动。该属性值同样定义在轮播图控制器的a链接上,同时设置控制器href值为容器    carousel的id名或其他样式识别符。

④data-slide-to属性:用来传递某个帧的下标,比如data-slide-to="2",可以直接跳转到这个指定的帧(下标从0开始计),同样定义在轮播图计数器的每个<li>标签上。

完整的图片轮播实现演示案例如下:

<!DOCTYPE html>
    <html>
      <head>
        <title>Bootstrap轮播插件</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/bootstrap.min.css" rel="stylesheet">
      </head>
      <body>
        <div id="slidershow" class="carousel slide" data-ride="carousel">
           <!-- 设置图片轮播计数器 -->
           <ol class="carousel-indicators">
              <li class="active" data-target="#slidershow" data-slide-to="0"></li>
              <li data-target="#slidershow" data-slide-to="1"></li>
              <li data-target="#slidershow" data-slide-to="2"></li>
           </ol>
           <!-- 设置轮播图片 -->
           <div class="carousel-inner">
               <div class="item active">
                   <a href="#">
                    <img src="images/carousel1.jpg" style=" height:400px;margin:0 auto;">
                   </a>
                   <div class="carousel-caption">
                        <h3>图片标题1</h3>
                        <p>描述内容1...</p>
                   </div>
                </div>
                <div class="item">
                    <a href="#">
                    <img src="images/carousel2.jpg"  style="height:400px;margin:0 auto;">
                    </a>
                    <div class="carousel-caption">
                        <h3>图片标题2</h3>
                        <p>描述内容2...</p>
                    </div>
                </div>
                <div class="item">
                    <a href="#">
                    <img src="images/carousel3.jpg" style=" height:400px;margin:0 auto;"></a>
                    <div class="carousel-caption">
                        <h3>图片标题3</h3>
                        <p>描述内容3...</p>
                    </div>
               </div>
           </div>
           <!-- 设置轮播图片控制器 -->
           <a class="left carousel-control" href="#slidershow" role="button" data-slide="prev">
             <span class="glyphicon glyphicon-chevron-left"></span>
           </a>
           <a class="right carousel-control" href="#slidershow" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
           </a>
        </div>
        <footer class="footer navbar-fixed-bottom ">
            <div class="container"> </div>
        </footer>
        <script src="jquery/jquery-1.11.0.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
      </body>
    </html>

      </body>
    </html>

Guess you like

Origin blog.csdn.net/zm321917/article/details/125100633