- 自由主题
-
三大框架
-
Angular
-
Angular HOME
- AngularJS extends HTML with new attributes.
AngularJS is perfect for Single Page Applications (SPAs).
AngularJS is easy to learn.
- 子主题 2
- React
- Vue
-
自动化工具
-
Node
- npm
- nvm
- webpack
- bower
- gulp
-
三大基础
-
CSS
-
CSS tutorial
-
HOME
- CSS is a language that describes the style of an HTML document.
CSS describes how HTML elements should be displayed.
- Syntax
-
how to
- External style sheet
Internal style sheet
Inline style
-
colors
- a valid color name - like "red"
- an RGB value - like "rgb(255, 0, 0)"
- a HEX value - like "#ff0000"
-
Bg
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
-
borders
- dotted - Defines a dotted border
- dashed - Defines a dashed border
- solid - Defines a solid border
- double - Defines a double border
- groove - Defines a 3D grooved border. The effect depends on the border-color value
- ridge - Defines a 3D ridged border. The effect depends on the border-color value
- inset - Defines a 3D inset border. The effect depends on the border-color value
- outset - Defines a 3D outset border. The effect depends on the border-color value
- none - Defines no border
- hidden - Defines a hidden border
-
margins
- All the margin properties can have the following values:
- auto - the browser calculates the margin
- length - specifies a margin in px, pt, cm, etc.
- % - specifies a margin in % of the width of the containing element
- inherit - specifies that the margin should be inherited from the parent element
-
padding
- All the padding properties can have the following values:
- length - specifies a padding in px, pt, cm, etc.
- % - specifies a padding in % of the width of the containing element
- inherit - specifies that the padding should be inherited from the parent element
-
H/W
- Note: The height and width properties do not include padding, borders, or margins; they set the height/width of the area inside the padding, border, and margin of the element!
-
box model
- box parts
- Explanation of the different parts:
- Content - The content of the box, where text and images appear
- Padding - Clears an area around the content. The padding is transparent
- Border - A border that goes around the padding and content
- Margin - Clears an area outside the border. The margin is transparent
- The box model allows us to add a border around elements, and to define space between elements.
- Width and Height of an Element
- Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.
-
Outline
- The CSS outline properties specify the style, color, and width of an outline.
An outline is a line that is drawn around elements (outside the borders) to make the element "stand out".
However, the outline property is different from the border property - The outline is NOT a part of an element's dimensions; the element's total width and height is not affected by the width of the outline.
- outline style
- Note: None of the OTHER CSS outline properties described below will have ANY effect unless the outline-style property is set!
- dotted - Defines a dotted outline
- dashed - Defines a dashed outline
- solid - Defines a solid outline
- double - Defines a double outline
- groove - Defines a 3D grooved outline. The effect depends on the outline-color value
- ridge - Defines a 3D ridged outline. The effect depends on the outline-color value
- inset - Defines a 3D inset outline. The effect depends on the outline-color value
- outset - Defines a 3D outset outline. The effect depends on the outline-color value
- none - Defines no outline
- hidden - Defines a hidden outline
-
text
- Note: For W3C compliant CSS: If you define the color property, you must also define the background-color
- Note: It is not recommended to underline text that is not a link, as this often confuses the reader.
- Text Transformation
- p.uppercase {
text-transform: uppercase;
}
p.lowercase {
text-transform: lowercase;
}
p.capitalize {
text-transform: capitalize;
}
- 子主题 4
- Property Description
- color Sets the color of text
- direction Specifies the text direction/writing direction
- letter-spacing Increases or decreases the space between characters in a text
- line-height Sets the line height
- text-align Specifies the horizontal alignment of text
- text-decoration Specifies the decoration added to text
- text-indent Specifies the indentation of the first line in a text-block
- text-shadow Specifies the shadow effect added to text
- text-transform Controls the capitalization of text
- unicode-bidi Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same document
- vertical-align Sets the vertical alignment of an element
- white-space Specifies how white-space inside an element is handled
- word-spacing Increases or decreases the space between words in a text
-
fonts
- Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.
-
icons
- How To Add Icons
The simplest way to add an icon to your HTML page, is with an icon library, such as Font Awesome.
Add the name of the specified icon class to any inline HTML element (like <i> or <span>).
All the icons in the icon libraries below, are scalable vectors that can be customized with CSS (size, color, shadow, etc.)
-
links
- The four links states are:
- a:link - a normal, unvisited link
- a:visited - a link the user has visited
- a:hover - a link when the user mouses over it
- a:active - a link the moment it is clicked
- When setting the style for several link states, there are some order rules:
a:hover MUST come after a:link and a:visited
a:active MUST come after a:hover
-
lists
- Property Description
- list-style Sets all the properties for a list in one declaration
- list-style-image Specifies an image as the list-item marker
- list-style-position Specifies if the list-item markers should appear inside or outside the content flow
- list-style-type Specifies the type of list-item marker
-
tables
- CSS Table Properties
- Property Description
- border Sets all the border properties in one declaration
- border-collapse Specifies whether or not table borders should be collapsed
- border-spacing Specifies the distance between the borders of adjacent cells
- caption-side Specifies the placement of a table caption
- empty-cells Specifies whether or not to display borders and background on empty cells in a table
- table-layout Sets the layout algorithm to be used for a table
-
display
- CSS Display/Visibility Properties
- Property Description
- display Specifies how an element should be displayed
- visibility Specifies whether or not an element should be visible
-
position
- static
- HTML elements are positioned static by default.
- Static positioned elements are not affected by the top, bottom, left, and right properties.
- An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:
- relative
- positioned relative to its normal position.
- Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.
- fixed
- An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.
- A fixed element does not leave a gap in the page where it would normally have been located.
- absolute
- An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
- However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
- Note: A "positioned" element is one whose position is anything except static.
- overlapping elements
- When elements are positioned, they can overlap other elements.
- The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).
- An element can have a positive or negative stack order:
- all css positioning property
- Property Description
- bottom Sets the bottom margin edge for a positioned box
- clip Clips an absolutely positioned element
- cursor Specifies the type of cursor to be displayed
- left Sets the left margin edge for a positioned box
- overflow Specifies what happens if content overflows an element's box
- overflow-x Specifies what to do with the left/right edges of the content if it overflows the element's content area
- overflow-y Specifies what to do with the top/bottom edges of the content if it overflows the element's content area
- position Specifies the type of positioning for an element
- right Sets the right margin edge for a positioned box
- top Sets the top margin edge for a positioned box
- z-index Sets the stack order of an element
-
overflow
- The CSS overflow property specifies whether to clip content or to add scrollbars when the content of an element is too big to fit in a specified area.
- The overflow property has the following values:
visible - Default. The overflow is not clipped. It renders outside the element's box
hidden - The overflow is clipped, and the rest of the content will be invisible
scroll - The overflow is clipped, but a scrollbar is added to see the rest of the content
auto - If overflow is clipped, a scrollbar should be added to see the rest of the content
Note: The overflow property only works for block elements with a specified height.
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).
-
float
- The float property specifies whether or not an element should float.
- The clear property is used to control the behavior of floating elements.
- The clearfix Hack - overflow: auto;
If an element is taller than the element containing it, and it is floated, it will overflow outside of its container.
Then we can add overflow: auto; to the containing element to fix this problem:
- Web Layout Example
It is common to do entire web layouts using the float property:
-
inline-block
- The inline-block Value
It has been possible for a long time to create a grid of boxes that fills the browser width and wraps nicely (when the browser is resized), by using the float property.
However, the inline-block value of the display property makes this even easier.
inline-block elements are like inline elements but they can have a width and a height.
-
align
- CSS Layout - Horizontal & Vertical Align
- Center Align Elements
To horizontally center a block element (like <div>), use margin: auto;
Setting the width of the element will prevent it from stretching out to the edges of its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins:
-
combinators
- A combinator is something that explains the relationship between the selectors.
- There are four different combinators in CSS3:
- 后代Fn:descendant selector (space)
- 子代F1:child selector (>)
- 邻系:adjacent sibling selector (+)
- 同系:general sibling selector (~)
-
pseudo-classes
- What are Pseudo-classes?
- A pseudo-class is used to define a special state of an element.
- Style an element when a user mouses over it
- Style visited and unvisited links differently
- Style an element when it gets focus
- Syntax
The syntax of pseudo-classes:
selector:pseudo-class {
property:value;
}
- Anchor Pseudo-classes
Links can be displayed in different ways:
- Pseudo-classes and CSS Classes
Pseudo-classes can be combined with CSS classes:
When you hover over the link in the example, it will change color:
- Hover on <div>
An example of using the :hover pseudo-class on a <div> element:
- Simple Tooltip Hover
Hover over a <div> element to show a <p> element (like a tooltip):
p {
display: none;
background-color: yellow;
padding: 20px;
}
div:hover p {
display: block;
}
- CSS - The :first-child Pseudo-class
- Match the first <i> element in all <p> elements
p i:first-child {
color: blue;
}
- Match all <i> elements in all first child <p> elements
p:first-child i {
color: blue;
}
- CSS - The :lang Pseudo-class
The :lang pseudo-class allows you to define special rules for different languages.
In the example below, :lang defines the quotation marks for <q> elements with lang="no":
- 伪类和为元素
- All CSS Pseudo Classes
- Selector Example Example description
- :active a:active Selects the active link
- :checked input:checked Selects every checked <input> element
- :disabled input:disabled Selects every disabled <input> element
- :empty p:empty Selects every <p> element that has no children
- :enabled input:enabled Selects every enabled <input> element
- :first-child p:first-child Selects every <p> elements that is the first child of its parent
- :first-of-type p:first-of-type Selects every <p> element that is the first <p> element of its parent
- :focus input:focus Selects the <input> element that has focus
- :hover a:hover Selects links on mouse over
- :in-range input:in-range Selects <input> elements with a value within a specified range
- :invalid input:invalid Selects all <input> elements with an invalid value
- :lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it"
- :last-child p:last-child Selects every <p> elements that is the last child of its parent
- :last-of-type p:last-of-type Selects every <p> element that is the last <p> element of its parent
- :link a:link Selects all unvisited links
- :not(selector) :not(p) Selects every element that is not a <p> element
- :nth-child(n) p:nth-child(2) Selects every <p> element that is the second child of its parent
- :nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the second child of its parent, counting from the last child
- :nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the second <p> element of its parent, counting from the last child
- :nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the second <p> element of its parent
- :only-of-type p:only-of-type Selects every <p> element that is the only <p> element of its parent
- :only-child p:only-child Selects every <p> element that is the only child of its parent
- :optional input:optional Selects <input> elements with no "required" attribute
- :out-of-range input:out-of-range Selects <input> elements with a value outside a specified range
- :read-only input:read-only Selects <input> elements with a "readonly" attribute specified
- :read-write input:read-write Selects <input> elements with no "readonly" attribute
- :required input:required Selects <input> elements with a "required" attribute specified
- :root root Selects the document's root element
- :target #news:target Selects the current active #news element (clicked on a URL containing that anchor name)
- :valid input:valid Selects all <input> elements with a valid value
- :visited a:visited Selects all visited links
- All CSS Pseudo Elements
- Selector Example Example description
- ::after p::after Insert content after every <p> element
- ::before p::before Insert content before every <p> element
- ::first-letter p::first-letter Selects the first letter of every <p> element
- ::first-line p::first-line Selects the first line of every <p> element
- ::selection p::selection Selects the portion of an element that is selected by a user
-
Pseudo-Elements
- Style the first letter, or line, of an element
Insert content before, or after, the content of an element
- selector::pseudo-element {
property:value;
}
- The ::first-letter Pseudo-element
- The ::first-line Pseudo-element
- Pseudo-elements and CSS Classes
-
opacity/transparency
- Transparent Hover Effect
- The opacity property is often used together with the :hover selector to change the opacity on mouse-over:
-
navigation bar
- Navigation Bar = List of Links
ul>li*n>a
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li a {
display: block;
width: 60px;
background-color: #dddddd;
}
- ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
border: 1px solid #555;
}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
li {
text-align: center;
border-bottom: 1px solid #555;
}
li:last-child {
border-bottom: none;
}
li a.active {
background-color: #4CAF50;
color: white;
}
li a:hover:not(.active) {
background-color: #555;
color: white;
}
- body {margin: 0;}
ul.sidenav {
list-style-type: none;
margin: 0;
padding: 0;
width: 25%;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
ul.sidenav li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
ul.sidenav li a.active {
background-color: #4CAF50;
color: white;
}
ul.sidenav li a:hover:not(.active) {
background-color: #555;
color: white;
}
div.content {
margin-left: 25%;
padding: 1px 16px;
height: 1000px;
}
@media screen and (max-width: 1050px){
ul.sidenav {
width:100%;
height:auto;
position:relative;
}
ul.sidenav li a {
float: left;
padding: 15px;
}
div.content {margin-left:0;}
}
@media screen and (max-width: 400px){
ul.sidenav li a {
text-align: center;
float: none;
}
}
-
dropdowns
- basic example
- <style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the text below to open the dropdown content.</p>
<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
-
tooltip
- A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element:
- .tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
-
image gallery
- div.img {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}
div.img:hover {
border: 1px solid #777;
}
div.img img {
width: 100%;
height: auto;
}
div.desc {
padding: 15px;
text-align: center;
}
-
image sprites
- An image sprite is a collection of images put into a single image.
- A web page with many images can take a long time to load and generates multiple server requests.
- Using image sprites will reduce the number of server requests and save bandwidth.
-
attribute selectors
- CSS [attribute] Selector
- CSS [attribute="value"] Selector
- CSS [attribute~="value"] Selector
- CSS [attribute|="value"] Selector
- CSS [attribute^="value"] Selector
- CSS [attribute$="value"] Selector
- CSS [attribute*="value"] Selector
- forms
-
counters
- body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}
-
CSS3
-
rounded corners
- CSS3 border-radius Property
-
border images
- The CSS3 border-image property allows you to specify an image to be used instead of the normal border around an element.
-
backgrounds
- CSS3 Background Properties
- Property Description
- background A shorthand property for setting all the background properties in one declaration
- background-clip Specifies the painting area of the background
- background-image Specifies one or more background images for an element
- background-origin Specifies where the background image(s) is/are positioned
- background-size Specifies the size of the background image(s)
- colors
-
gradient
- Linear Gradients (goes down/up/left/right/diagonally)
- Radial Gradients (defined by their center)
-
shadow effects
- text-shadow
- box-shadow
-
text
- Property Description
- text-align-last Specifies how to align the last line of a text
- text-emphasis A shorthand for setting text-emphasis-style and text-emphasis-color in one declaration
- text-justify Specifies how justified text should be aligned and spaced
- text-overflow Specifies how overflowed content that is not displayed should be signaled to the user
- word-break Specifies line breaking rules for non-CJK scripts
- word-wrap Allows long words to be able to be broken and wrap onto the next line
-
fonts
- Descriptor Values Description
- font-family name Required. Defines a name for the font
- src URL Required. Defines the URL of the font file
- font-stretch normal
- condensed
- ultra-condensed
- extra-condensed
- semi-condensed
- expanded
- semi-expanded
- extra-expanded
- ultra-expanded Optional. Defines how the font should be stretched. Default is "normal"
- font-style normal
- italic
- oblique Optional. Defines how the font should be styled. Default is "normal"
- font-weight normal
- bold
- 100
- 200
- 300
- 400
- 500
- 600
- 700
- 800
- 900 Optional. Defines the boldness of the font. Default is "normal"
- unicode-range unicode-range Optional. Defines the range of UNICODE characters the font supports. Default is "U+0-10FFFF"
- 2d transform
- 3d transform
- transitions
- animations
- images
- buttons
- pagination examples
- multiple columns
- user interface
- box sizing
- flexible box
-
Responsive Web Design
-
intro
- What is Responsive Web Design?
Responsive web design makes your web page look good on all devices.
Responsive web design uses only HTML and CSS.
Responsive web design is not a program or a JavaScript.
-
The Viewport
- Viewport
- The viewport is the user's visible area of a web page.
The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.
Before tablets and mobile phones, web pages were designed only for computer screens, and it was common for web pages to have a static design and a fixed size.
Then, when we started surfing the internet using tablets and mobile phones, fixed size web pages were too large to fit the viewport. To fix this, browsers on those devices scaled down the entire web page to fit the screen.
This was not perfect!! But a quick fix.
- Setting The Viewport
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- Size Content to The Viewport
- Users are used to scroll websites vertically on both desktop and mobile devices - but not horizontally!
So, if the user is forced to scroll horizontally, or zoom out, to see the whole web page it results in a poor user experience.
Some additional rules to follow:
1. Do NOT use large fixed width elements - For example, if an image is displayed at a width wider than the viewport it can cause the viewport to scroll horizontally. Remember to adjust this content to fit within the width of the viewport.
2. Do NOT let the content rely on a particular viewport width to render well - Since screen dimensions and width in CSS pixels vary widely between devices, content should not rely on a particular viewport width to render well.
3. Use CSS media queries to apply different styling for small and large screens - Setting large absolute CSS widths for page elements, will cause the element to be too wide for the viewport on a smaller device. Instead, consider using relative width values, such as width: 100%. Also, be careful of using large absolute positioning values. It may cause the element to fall outside the viewport on small devices.
-
Grid View
- Many web pages are based on a grid-view, which means that the page is divided into columns:
- Building a Responsive Grid-View
box-sizing: border-box;
-
Media Queries
- @media only screen and (max-width: 500px) {
body {
background-color: lightblue;
}
}
-
Images
- If the width property is set to 100%, the image will be responsive and scale up and down:
- Using The max-width Property
- Add an Image to The Example Web Page
- div {
width: 100%;
height: 400px;
background-image: url('img_flowers.jpg');
background-repeat: no-repeat;
background-size: contain;
border: 1px solid red;
}
- HTML5 <picture> Element
- Videos
- Frameworks
- Templates
-
javascript
-
DOM
-
DOM HTML tree
- With the object model, JavaScript gets all the power it needs to create dynamic HTML:
- JavaScript can change all the HTML elements in the page
- JavaScript can change all the HTML attributes in the page
- JavaScript can change all the CSS styles in the page
- JavaScript can remove existing HTML elements and attributes
- JavaScript can add new HTML elements and attributes
- JavaScript can react to all existing HTML events in the page
- JavaScript can create new HTML events in the page
- What You Will Learn
- How to change the content of HTML elements
- How to change the style (CSS) of HTML elements
- How to react to HTML DOM events
- How to add and delete HTML elements
- What is the DOM?
- "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
- The W3C DOM standard is separated into 3 different parts:
- Core DOM - standard model for all document types
- XML DOM - standard model for XML documents
- HTML DOM - standard model for HTML documents
- The HTML DOM is a standard object model and programming interface for HTML. It defines:
- The HTML elements as objects
- The properties of all HTML elements
- The methods to access all HTML elements
- The events for all HTML elements
- In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
-
JavaScript - HTML DOM Methods
- HTML DOM methods are actions you can perform (on HTML Elements).
- HTML DOM properties are values (of HTML Elements) that you can set or change.
- The DOM Programming Interface
- In the DOM, all HTML elements are defined as objects.
- The programming interface is the properties and methods of each object.
- A property is a value that you can get or set (like changing the content of an HTML element).
- A method is an action you can do (like add or deleting an HTML element).
-
JavaScript HTML DOM Document
- The HTML DOM document object is the owner of all other objects in your web page.
- Finding HTML Elements
- Method Description
- document.getElementById(id) Find an element by element id
- document.getElementsByTagName(name) Find elements by tag name
- document.getElementsByClassName(name) Find elements by class name
- Changing HTML Elements
- Method Description
- element.innerHTML = new html content Change the inner HTML of an element
- element.attribute = new value Change the attribute value of an HTML element
- element.setAttribute(attribute, value) Change the attribute value of an HTML element
- element.style.property = new style Change the style of an HTML element
- Adding and Deleting Elements
- Method Description
- document.createElement(element) Create an HTML element
- document.removeChild(element) Remove an HTML element
- document.appendChild(element) Add an HTML element
- document.replaceChild(element) Replace an HTML element
- document.write(text) Write into the HTML output stream
- Adding Events Handlers
- Method Description
- document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event
- Finding HTML Objects
- Property Description DOM
- document.anchors Returns all <a> elements that have a name attribute 1
- document.applets Returns all <applet> elements (Deprecated in HTML5) 1
- document.baseURI Returns the absolute base URI of the document 3
- document.body Returns the <body> element 1
- document.cookie Returns the document's cookie 1
- document.doctype Returns the document's doctype 3
- document.documentElement Returns the <html> element 3
- document.documentMode Returns the mode used by the browser 3
- document.documentURI Returns the URI of the document 3
- document.domain Returns the domain name of the document server 1
- document.domConfig Obsolete. Returns the DOM configuration 3
- document.embeds Returns all <embed> elements 3
- document.forms Returns all <form> elements 1
- document.head Returns the <head> element 3
- document.images Returns all <img> elements 1
- document.implementation Returns the DOM implementation 3
- document.inputEncoding Returns the document's encoding (character set) 3
- document.lastModified Returns the date and time the document was updated 3
- document.links Returns all <area> and <a> elements that have a href attribute 1
- document.readyState Returns the (loading) status of the document 3
- document.referrer Returns the URI of the referrer (the linking document) 1
- document.scripts Returns all <script> elements 3
- document.strictErrorChecking Returns if error checking is enforced 3
- document.title Returns the <title> element 1
- document.URL Returns the complete URL of the document 1
-
JavaScript HTML DOM Elements
- This page teaches you how to find and access HTML elements in an HTML page.
- Finding HTML Elements
- Finding HTML elements by id
- Finding HTML elements by tag name
- Finding HTML elements by class name
- Finding HTML elements by CSS selectors
- Finding HTML elements by HTML object collections
- var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
-
JavaScript HTML DOM - Changing HTML
- The HTML DOM allows JavaScript to change the content of HTML elements.
-
JavaScript HTML DOM - Changing CSS
- The HTML DOM allows JavaScript to change the style of HTML elements.
- JavaScript HTML DOM Animation
- JavaScript HTML DOM Events
-
JavaScript HTML DOM EventListener
- The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
You can add many event handlers to one element.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.
-
JavaScript HTML DOM Navigation
- With the HTML DOM, you can navigate the node tree using node relationships.
- DOM Nodes
- According to the W3C HTML DOM standard, everything in an HTML document is a node:
- The entire document is a document node
- Every HTML element is an element node
- The text inside HTML elements are text nodes
- Every HTML attribute is an attribute node
- All comments are comment nodes
- Navigating Between Nodes
- parentNode
- childNodes[nodenumber]
- firstChild
- lastChild
- nextSibling
- previousSibling
- The nodeName Property
- nodeName is read-only
- nodeName of an element node is the same as the tag name
- nodeName of an attribute node is the attribute name
- nodeName of a text node is always #text
- nodeName of the document node is always #document
- Note: nodeName always contains the uppercase tag name of an HTML element.
- The nodeValue Property
- The nodeValue property specifies the value of a node.
- nodeValue for element nodes is undefined
- nodeValue for text nodes is the text itself
- nodeValue for attribute nodes is the attribute value
- The nodeType Property
- The most important node types are:
- Element type NodeType
- Element 1
- Attribute 2
- Text 3
- Comment 8
- Document 9
-
JavaScript HTML DOM Elements (Nodes)
- Creating New HTML Elements (Nodes)
- var para = document.createElement("p");
- var node = document.createTextNode("This is new.");
- para.appendChild(node);
- var element = document.getElementById("div1");
- element.appendChild(para);
- Creating new HTML Elements - insertBefore()
- Removing Existing HTML Elements
- parent.removeChild(child);
- The method node.remove() is implemented in the DOM 4 specification.
- But because of poor browser support, you should not use it.
- Replacing HTML Elements
- parent.replaceChild(para,child);
-
JavaScript HTML DOM Node List
- A node list is a collection of nodes
- HTML DOM Node List Length
-
ES
-
ES5
- JavaScript Forms
- JavaScript Objects
- In JavaScript, objects are king. If you understand objects, you understand JavaScript.
- Booleans can be objects (or primitive data treated as objects)
- Numbers can be objects (or primitive data treated as objects)
- Strings can be objects (or primitive data treated as objects)
- Dates are always objects
- Maths are always objects
- Regular expressions are always objects
- Arrays are always objects
- Functions are always objects
- Objects are objects
- Objects are Variables Containing Variables
- JavaScript variables can contain single values:
- var person = "John Doe";
- Objects are variables too. But objects can contain many values.
- The values are written as name : value pairs (name and value separated by a colon).
- Object Properties
- Objects written as name value pairs are similar to:
- Associative arrays in PHP
- Dictionaries in Python
- Hash tables in C
- Hash maps in Java
- Hashes in Ruby and Perl
- Object Methods
- Methods are actions that can be performed on objects.
- Creating a JavaScript Object
- Define and create a single object, using an object literal.
- Define and create a single object, with the keyword new.
- Define an object constructor, and then create objects of the constructed type.
- In ECMAScript 5, an object can also be created with the function Object.create().
- The two examples above do exactly the same. There is no need to use new Object().
- For simplicity, readability and execution speed, use the first one (the object literal method).
- Using an Object Constructor
- function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");
- The this Keyword
- In JavaScript, the thing called this, is the object that "owns" the JavaScript code.
The value of this, when used in a function, is the object that "owns" the function.
The value of this, when used in an object, is the object itself.
The this keyword in an object constructor does not have a value. It is only a substitute for the new object.
The value of this will become the new object when the constructor is used to create an object.
Note that this is not a variable. It is a keyword. You cannot change the value of this.
- Built-in JavaScript Constructors
- var x1 = new Object(); // A new Object object
- var x2 = new String(); // A new String object
- var x3 = new Number(); // A new Number object
- var x4 = new Boolean(); // A new Boolean object
- var x5 = new Array(); // A new Array object
- var x6 = new RegExp(); // A new RegExp object
- var x7 = new Function(); // A new Function object
- var x8 = new Date(); // A new Date object
- var x1 = {}; // new object
- var x2 = ""; // new primitive string
- var x3 = 0; // new primitive number
- var x4 = false; // new primitive boolean
- var x5 = []; // new array object
- var x6 = /()/ // new regexp object
- var x7 = function(){}; // new function object
- JavaScript Objects are Mutable
- Objects are mutable: They are addressed by reference, not by value.
- var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
var x = person;
x.age = 10; // This will change both x.age and person.age
- Note: JavaScript variables are not mutable. Only JavaScript objects.
- JavaScript Object Properties
- Properties are the most important part of any JavaScript object.
- Properties are the values associated with a JavaScript object.
- A JavaScript object is a collection of unordered properties.
- Properties can usually be changed, added, and deleted, but some are read only.
- Accessing JavaScript Properties
- objectName.property // person.age
- objectName["property"] // person["age"]
- objectName[expression] // x = "age"; person[x]
- JavaScript for...in Loop
- Adding New Properties
- Deleting Properties
- Property Attributes
- All properties have a name. In addition they also have a value.
The value is one of the property's attributes.
Other attributes are: enumerable, configurable, and writable.
These attributes define how the property can be accessed (is it readable?, is it writable?)
In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
- Prototype Properties
- JavaScript objects inherit the properties of their prototype.
- The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.
- JavaScript Object Methods
- JavaScript methods are the actions that can be performed on objects.
- A JavaScript method is a property containing a function definition.
- Methods are functions stored as object properties.
- Accessing Object Methods
- methodName : function() { code lines }
- objectName.methodName()
- Using Built-In Methods
- var x = message.toUpperCase();
- Adding New Methods
- JavaScript Object Prototypes
- Every JavaScript object has a prototype. The prototype is also an object.
- All JavaScript objects inherit their properties and methods from their prototype.
- All JavaScript objects inherit the properties and methods from their prototype.
Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
Objects created with new Date() inherit the Date.prototype.
The Object.prototype is on the top of the prototype chain.
All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.
- Creating a Prototype
- The standard way to create an object prototype is to use an object constructor function:
- function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
- The constructor function is the prototype for Person objects.
It is considered good practice to name constructor function with an upper-case first letter.
- Adding Properties and Methods to Objects
- Adding a Property to an Object
- Adding a Method to an Object
- Adding Properties to a Prototype
- To add a new property to a prototype, you must add it to the constructor function:
- function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English"
}
- Prototype properties can have prototype values (default values).
- Adding Methods to a Prototype
- Using the prototype Property
- Person.prototype.nationality = "English";
- Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
- JavaScript Function Definitions
- JavaScript functions are defined with the function keyword.
- You can use a function declaration or a function expression.
- Function Declarations
- function functionName(parameters) {
code to be executed
}
- Function Expressions
- var x = function (a, b) {return a * b};
- The function above is actually an anonymous function (a function without a name).
- Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
- The function above ends with a semicolon because it is a part of an executable statement.
- The Function() Constructor
- Most of the time, you can avoid using the new keyword in JavaScript.
- Function Hoisting
- Because of this, JavaScript functions can be called before they are declared:
- myFunction(5);
function myFunction(y) {
return y * y;
}
- Functions defined using an expression are not hoisted.
- Self-Invoking Functions
- (function () {
var x = "Hello!!"; // I will invoke myself
})();
- The function above is actually an anonymous self-invoking function (function without name).
- Functions Can Be Used as Values
- Functions are Objects
- A function defined as the property of an object, is called a method to the object.
- A function designed to create new objects, is called an object constructor.
- JavaScript Function Parameters
- A JavaScript function does not perform any checking on parameter values (arguments).
- Function Parameters and Arguments
- Function parameters(形参) are the names listed in the function definition.
- Function arguments(实参) are the real values passed to (and received by) the function.
- Parameter Rules
- JavaScript function definitions do not specify data types for parameters.
- JavaScript functions do not perform type checking on the passed arguments.
- JavaScript functions do not check the number of arguments received.
- Parameter Defaults
- If a function is called with missing arguments (less than declared), the missing values are set to: undefined
- Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:
- The Arguments Object
- JavaScript functions have a built-in object called the arguments object.
- Arguments are Passed by Value
- The parameters, in a function call, are the function's arguments.
- JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations.
- If a function changes an argument's value, it does not change the parameter's original value.
- Changes to arguments are not visible (reflected) outside the function.
- Objects are Passed by Reference
- In JavaScript, object references are values.
- Because of this, objects will behave like they are passed by reference:
- If a function changes an object property, it changes the original value.
- Changes to object properties are visible (reflected) outside the function.
- JavaScript Function Invocation
- JavaScript functions can be invoked in 4 different ways.
- Each method differs in how this is initialized.
- The this Keyword
- In JavaScript, the thing called this, is the object that "owns" the current code.
- The value of this, when used in a function, is the object that "owns" the function.
- Invoking a JavaScript Function
- You have already learned that the code inside a JavaScript function will execute when "something" invokes it.
The code in a function is not executed when the function is defined. It is executed when the function is invoked.
Some people use the term "call a function" instead of "invoke a function".
It is also quite common to say "call upon a function", "start a function", or "execute a function".
In this tutorial, we will use invoke, because a JavaScript function can be invoked without being called.
- The Global Object
- When a function is called without an owner object, the value of this becomes the global object.
- In a web browser the global object is the browser window.
- This example returns the window object as the value of this:
- Invoking a function as a global function, causes the value of this to be the global object.
- Using the window object as a variable can easily crash your program.
- Invoking a Function as a Method
- myObject.fullName();
- Invoking a function as an object method, causes the value of this to be the object itself.
- Invoking a Function with a Function Constructor
- var x = new myFunction("John","Doe");
- If a function invocation is preceded with the new keyword, it is a constructor invocation.
- Invoking a Function with a Function Method
- In JavaScript, functions are objects. JavaScript functions have properties and methods.
- call() and apply() are predefined JavaScript function methods. Both methods can be used to invoke a function, and both methods must have the owner object as first parameter.
- With call() or apply() you can set the value of this, and invoke a function as a new method of an existing object.
- JavaScript Closures
- JavaScript variables can belong to the local or global scope.
- Private variables can be made possible with closures.
- Variable Lifetime
- Global variables live as long as your application (your window / your web page) lives.
- Local variables have short lives. They are created when the function is invoked, and deleted when the function is finished.
- JavaScript Nested Functions
- In fact, in JavaScript, all functions have access to the scope "above" them.
- JSON
- JSON Syntax
- JSON: JavaScript Object Notation.
- JSON is a syntax for storing and exchanging data.
- JSON is an easier-to-use alternative to XML.
- {"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
- JSON Syntax Rules
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
- JSON Values
- A number (integer or floating point)
- A string (in double quotes)
- A Boolean (true or false)
- An array (in square brackets)
- An object (in curly braces)
- null
- JSON Objects
- JSON objects are written inside curly braces.
- JSON Arrays
- JSON Files
- JSON How To
- JSON Http Request
- A common use of JSON is to read data from a web server, and display the data in a web page.
- JSON Function Files
- A common use of JSON is to read data from a web server, and display the data in a web page.
- JSON SQL
- This example reads JSON data from a web server running PHP and MySQL:
- Tutorial
- intro
- JavaScript Can Change HTML Content:
document.getElementById("demo").innerHTML = "Hello JavaScript";
- JavaScript Can Change HTML Attributes:
document.getElementById('myImage').src='pic_bulbon.gif'
- JavaScript Can Change HTML Styles (CSS)
document.getElementById("demo").style.fontSize = "25px";
- JavaScript Can Hide/Show HTML Elements
- JavaScript Output
- JavaScript can "display" data in different ways:
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().
- JavaScript does NOT have any built-in print or display functions.
- JavaScript Keywords
- Keyword Description
- break Terminates a switch or a loop
- continue Jumps out of a loop and starts at the top
- debugger Stops the execution of JavaScript, and calls (if available) the debugging function
- do ... while Executes a block of statements, and repeats the block, while a condition is true
- for Marks a block of statements to be executed, as long as a condition is true
- function Declares a function
- if ... else Marks a block of statements to be executed, depending on a condition
- return Exits a function
- switch Marks a block of statements to be executed, depending on different cases
- try ... catch Implements error handling to a block of statements
- var Declares a variable
- JavaScript Type Operators
- Operator Description
- typeof Returns the type of a variable
- instanceof Returns true if an object is an instance of an object type
- JavaScript Comparison and Logical Operators
- Operator Description
- == equal to
- === equal value and equal type
- != not equal
- !== not equal value or not equal type
- > greater than
- < less than
- >= greater than or equal to
- <= less than or equal to
- ? ternary operator
- JavaScript Operator Precedence Values
- Value Operator Description Example
- 19 ( ) Expression grouping (3 + 4)
-
- 18 . Member person.name
- 18 [] Member person["name"]
-
- 17 () Function call myFunction()
- 17 new Create new Date()
-
- 16 ++ Postfix Increment i++
- 16 -- Postfix Decrement i--
-
- 15 ++ Prefix Increment ++i
- 15 -- Prefix Decrement --i
- 15 ! Logical not !(x==y)
- 15 typeof Type typeof x
-
- 14 * Multiplication 10 * 5
- 14 / Division 10 / 5
- 14 % Modulo division 10 % 5
- 14 ** Exponentiation 10 ** 2
-
- 13 + Addition 10 + 5
- 13 - Subtraction 10 - 5
-
- 12 << Shift left x << 2
- 12 >> Shift right x >> 2
-
- 11 < Less than x < y
- 11 <= Less than or equal x <= y
- 11 > Greater than x > y
- 11 >= Greater than or equal x >= y
-
- 10 == Equal x == y
- 10 === Strict equal x === y
- 10 != Unequal x != y
- 10 !== Strict unequal x !== y
-
- 6 && And x && y
- 5 || Or x || y
-
- 3 = Assignment x = y
- 3 += Assignment x += y
- 3 -= Assignment x -= y
- 3 *= Assignment x *= y
- 3 /= Assignment x /= y
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Scope
- In JavaScript, scope is the set of variables, objects, and functions you have access to.
- Local JavaScript Variables
- Global JavaScript Variables
- Automatically Global:
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
- Global Variables in HTML:
Your global variables (or functions) can overwrite window variables (or functions).
Any function, including the window object, can overwrite your global variables and functions.
- The Lifetime of JavaScript Variables:
The lifetime of a JavaScript variable starts when it is declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.
- Function Arguments:
Function arguments (parameters) work as local variables inside functions.
- JavaScript Events
-
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
- HTML Events
- Event Description
- onchange An HTML element has been changed
- onclick The user clicks an HTML element
- onmouseover The user moves the mouse over an HTML element
- onmouseout The user moves the mouse away from an HTML element
- onkeydown The user pushes a keyboard key
- onload The browser has finished loading the page
- JavaScript Strings
- his is the list of special characters that can be added to a text string with the backslash sign:
- Code Outputs
- \' single quote
- \" double quote
- \\ backslash
- \n new line
- \r carriage return
- \t tab
- \b backspace
- \f form feed
- JavaScript String Methods
- String Methods and Properties
Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
- String Length:str.length
- Finding a String in a String
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
- Searching for a String in a String:str.search('')
Did You Notice?
The two methods, indexOf() and search(), are equal.
They accept the same arguments (parameters), and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.
You will learn more about powerful search values in the chapter about regular expressions.
- Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
- Replacing String Content
The replace() method replaces a specified value with another value in a string:
var n = str.replace(/Microsoft/g,"W3Schools");
- Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase()||toLowerCase():
- The concat() Method
concat() joins two or more strings:
- All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
- Extracting String Characters
- There are 2 safe methods for extracting string characters:
- charAt(position)
- The charAt() method returns the character at a specified index (position) in a string:
- charCodeAt(position)
- The charCodeAt() method returns the unicode of the character at a specified index in a string:
- Accessing a String as an Array is Unsafe
- var str = "HELLO WORLD";
str[0]; // returns H
This is unsafe and unpredictable:
It does not work in all browsers (not in IE5, IE6, IE7)
It makes strings look like arrays (but they are not)
str[0] = "H" does not give an error (but does not work)
- Converting a String to an Array
- A string can be converted to an array with the split() method:
- If the separator is omitted, the returned array will contain the whole string in index [0].
- If the separator is "", the returned array will be an array of single characters:
- JavaScript Numbers
- JavaScript Numbers are Always 64-bit Floating Point
- Precision
Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
var x = 999999999999999; // x will be 999999999999999
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3
var x = 0.2 + 0.1; // x will be 0.30000000000000004
var y = 9999999999999999; // y will be 10000000000000000
- NaN - Not a Number
- Numbers Can be Objects:
var x = 123;
var y = new Number(123);
// typeof x returns number
// typeof y returns object
- JavaScript Number Methods
- Number Methods and Properties
Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
- The toString() Method
toString() returns a number as a string.
All number methods can be used on any type of numbers (literals, variables, or expressions):
- The toExponential() Method
toExponential() returns a string, with a number rounded and written using exponential notation.
A parameter defines the number of characters behind the decimal point:
- The toFixed() Method
toFixed() returns a string, with the number written with a specified number of decimals:
- The toPrecision() Method
toPrecision() returns a string, with a number written with a specified length:
- The valueOf() Method
valueOf() returns a number as a number.
In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).
The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.
There is no reason to use it in your code.
- Converting Variables to Numbers
- The Number() method
- The parseInt() method
- The parseFloat() method
- JavaScript Math Object
- Math.PI;
- Math.round()
- Math.pow()
- Math.sqrt()
- Math.abs()
- Math.ceil()
- Math.floor()
- Math.sin()
- Math.cos()
- Math.min() and Math.max()
- Math.random()
- Math Properties (Constants)
- Math.E // returns Euler's number
- Math.PI // returns PI
- Math.SQRT2 // returns the square root of 2
- Math.SQRT1_2 // returns the square root of 1/2
- Math.LN2 // returns the natural logarithm of 2
- Math.LN10 // returns the natural logarithm of 10
- Math.LOG2E // returns base 2 logarithm of E
- Math.LOG10E // returns base 10 logarithm of E
- JavaScript Random
- Math.random()
- JavaScript Random Integers
- A Proper Random Function:
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
- JavaScript Dates
- JavaScript Date Formats
- Creating Date Objects
- new Date()
- new Date(milliseconds)
- new Date(dateString)
- new Date(year, month, day, hours, minutes, seconds, milliseconds)
- Time Zones
- When setting a date, without specifying the time zone, JavaScript will use the browser's time zone.
- When getting a date, without specifying the time zone, the result is converted to the browser's time zone.
- In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.
- JavaScript Date Formats
- JavaScript Date Input
- There are generally 4 types of JavaScript date input formats:
- Type Example
- ISO Date "2015-03-25" (The International Standard)
- var d = new Date("2015-03-25");
- Short Date "03/25/2015" or "2015/03/25"
- var d = new Date("03/25/2015");
- Long Date "Mar 25 2015" or "25 Mar 2015"
- var d = new Date("Mar 25 2015");
- Full Date "Wednesday March 25 2015"
- JavaScript Date Output
- Independent of input format, JavaScript will (by default) output dates in full text string format:
- Wed Mar 25 2015 08:00:00 GMT+0800 (中国标准时间)
- JavaScript Date Methods
- Method Description
- getDate() Get the day as a number (1-31)
- getDay() Get the weekday as a number (0-6)
- getFullYear() Get the four digit year (yyyy)
- getHours() Get the hour (0-23)
- getMilliseconds() Get the milliseconds (0-999)
- getMinutes() Get the minutes (0-59)
- getMonth() Get the month (0-11)
- getSeconds() Get the seconds (0-59)
- getTime() Get the time (milliseconds since January 1, 1970)
- Date Set Methods
- setDate() Set the day as a number (1-31)
- setFullYear() Set the year (optionally month and day)
- setHours() Set the hour (0-23)
- setMilliseconds() Set the milliseconds (0-999)
- setMinutes() Set the minutes (0-59)
- setMonth() Set the month (0-11)
- setSeconds() Set the seconds (0-59)
- setTime() Set the time (milliseconds since January 1, 1970)
- JavaScript Arrays
- The Difference Between Arrays and Objects
- In JavaScript, arrays use numbered indexes.
- In JavaScript, objects use named indexes.
- Arrays are a special kind of objects, with numbered indexes.
- When to Use Arrays. When to use Objects.
- You should use objects when you want the element names to be strings (text).
- You should use arrays when you want the element names to be numbers.
- JavaScript Array Methods
- Converting Arrays to Strings: toString()
The join() method also joins all array elements into a string.
- Popping and Pushing
- Shifting Elements
- The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:
- Changing Elements
- Deleting Elements:
Using delete may leave undefined holes in the array. Use pop() or shift() instead.
- Splicing an Array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
- Using splice() to Remove Elements
- Joining Arrays
The concat() method creates a new array by concatenating two arrays
- Slicing an Array
- The valueOf() Method:
The valueOf() method is the default behavior for an array. It converts an array to a primitive
value.
All JavaScript objects have a valueOf() and a toString() method.
- Sorting Arrays
- SortArrays
- The sort() method sorts an array alphabetically:
- fruits.sort();
- Reversing an Array
- The reverse() method reverses the elements in an array.
- Numeric Sort
- By default, the sort() function sorts values as strings.
- points.sort(function(a, b){return a - b});
- Try it Yourself »
- The Compare Function
- The compare function should return a negative, zero, or positive value, depending on the arguments:
- function(a, b){return a-b}
- Sorting an Array in Random Order
- points.sort(function(a, b){return 0.5 - Math.random()});
- Try it Yourself »
- Sorting Object Arrays
- The solution is to write a compare function to compare the property values:
- cars.sort(function(a, b){return a.year - b.year});
- Comparing string properties is a little more complex::
- cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
- JavaScript Booleans
- A JavaScript Boolean represents one of two values: true or false.
- Everything Without a "Real" is False
- JavaScript Comparison and Logical Operators
- Operator Description Comparing Returns Try it
- == equal to x == 8 false Try it »
- x == 5 true Try it »
- x == "5" true Try it »
- === equal value and equal type x === 5 true Try it »
- x === "5" false Try it »
- != not equal x != 8 true Try it »
- !== not equal value or not equal type x !== 5 false Try it »
- x !== "5" true Try it »
- x !== 8 true Try it »
- > greater than x > 8 false Try it »
- < less than x < 8 true Try it »
- >= greater than or equal to x >= 8 false Try it »
- <= less than or equal to x <= 8 true
- Logical Operators
- Operator Description Example Try it
- && and (x < 10 && y > 1) is true Try it »
- || or (x == 5 || y == 5) is false Try it »
- ! not !(x == y) is true
- Conditions
- if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
- JavaScript Switch Statement
- switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
- JavaScript For Loop
- Different Kinds of Loops
- for - loops through a block of code a number of times
- for/in - loops through the properties of an object
- while - loops through a block of code while a specified condition is true
- do/while - also loops through a block of code while a specified condition is true
- JavaScript While Loop
- while (condition) {
code block to be executed
}
- do {
code block to be executed
}
while (condition);
- JavaScript Break and Continue
- The Break Statement
- It was used to "jump out" of a switch() statement.
- The Continue Statement
- The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
- JavaScript Labels
- break labelname;
- continue labelname;
- JavaScript Type Conversion
- JavaScript Data Types
- In JavaScript there are 5 different data types that can contain values:
- string
- number
- boolean
- object
- function
- And 2 data types that cannot contain values:
- null
- undefined
- There are 35types of objects:
- Object
- Date
- Array
- Regexp
- JSON
- The typeof Operator
- The constructor Property
- The constructor property returns the constructor function for all JavaScript variables.
- JavaScript Type Conversion
- The Unary + Operator
- The unary + operator can be used to convert a variable to a number:
- Automatic Type Conversion
- The result is not always what you expect:
- JavaScript Regular Expressions
- /pattern/modifiers;
- /w3schools/i is a regular expression.
- w3schools is a pattern (to be used in a search).
- i is a modifier (modifies the search to be case-insensitive).
- Regular Expression Modifiers
- Modifier Description
- i Perform case-insensitive matching
- g Perform a global match (find all matches rather than stopping after the first match)
- m Perform multiline matching
- Regular Expression Patterns
- Expression Description
- [abc] Find any of the characters between the brackets
- [0-9] Find any of the digits between the brackets
- (x|y) Find any of the alternatives separated with |
- Metacharacter Description
- \d Find a digit
- \s Find a whitespace character
- \b Find a match at the beginning or at the end of a word
- \uxxxx Find the Unicode character specified by the hexadecimal number xxxx
- Quantifier Description
- n+ Matches any string that contains at least one n
- n* Matches any string that contains zero or more occurrences of n
- n? Matches any string that contains zero or one occurrences of n
- JavaScript Errors - Throw and Try to Catch
- JavaScript Debugging
- The console.log() Method
- Setting Breakpoints
- The debugger Keyword
- Major Browsers' Debugging Tools
- JavaScript Hoisting
- Hoisting is JavaScript's default behavior of moving declarations to the top.
- JavaScript Declarations are Hoisted
- In JavaScript, a variable can be declared after it has been used.
- JavaScript Initializations are Not Hoisted
- JavaScript only hoists declarations, not initializations.
- Declare Your Variables At the Top !
- JavaScript Use Strict
- "use strict"; Defines that JavaScript code should be executed in "strict mode".
- Not Allowed in Strict Mode
- Using a variable, without declaring it, is not allowed:
- Using an object, without declaring it, is not allowed:
- Deleting a variable (or object) is not allowed.
- Deleting a function is not allowed.
- Duplicating a parameter name is not allowed:
- Writing to a read-only property is not allowed:
- Writing to a get-only property is not allowed:
- Deleting an undeletable property is not allowed:
- The string "eval" cannot be used as a variable:
- The string "arguments" cannot be used as a variable:
- The with statement is not allowed:
- For security reasons, eval() is not allowed to create variables in the scope from which it was called:
- JavaScript Style Guide and Coding Conventions
- JavaScript Best Practices
- Avoid global variables, avoid new, avoid ==, avoid eval()
- JavaScript Common Mistakes
- Accidentally Using the Assignment Operator
- Expecting Loose Comparison
- Confusing Addition & Concatenation
- Addition is about adding numbers.
- Concatenation is about adding strings.
- var x = 10 + 5; // the result in x is 15
- var x = 10 + "5"; // the result in x is "105"
- Misunderstanding Floats
- All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats).
- Breaking a JavaScript String
- Misplacing Semicolon
- if (x == 19);
- Breaking a Return Statement
- Accessing Arrays with Named Indexes
- Ending an Array Definition with a Comma
- points = [40, 100, 1, 5, 25, 10,];
- Ending an Object Definition with a Comma
- Undefined is Not Null
- With JavaScript, null is for objects, undefined is for variables, properties, and methods.
- To be null, an object has to be defined, otherwise it will be undefined.
- If you want to test if an object exists, this will throw an error if the object is undefined:
- if (typeof myObj !== "undefined" && myObj !== null)
- Expecting Block Level Scope
- JavaScript Performance
- Reduce Activity in Loops
- var i;
var l = arr.length;
for (i = 0; i < l; i++) {
- Reduce DOM Access
- Accessing the HTML DOM is very slow, compared to other JavaScript statements.
- Reduce DOM Size
- Avoid Unnecessary Variables
- Delay JavaScript Loading
- Avoid Using with
- JavaScript Reserved Words
- JavaScript Reserved Words
- abstract arguments boolean break byte
- case catch char class* const
- continue debugger default delete do
- double else enum* eval export*
- extends* false final finally float
- for function goto if implements
- import* in instanceof int interface
- let long native new null
- package private protected public return
- short static super* switch synchronized
- this throw throws transient true
- try typeof var void volatile
- while with yield
- JavaScript Objects, Properties, and Methods
- Array Date eval function hasOwnProperty
- Infinity isFinite isNaN isPrototypeOf length
- Math NaN name Number Object
- prototype String toString undefined valueOf
- Java Reserved Words
- getClass java JavaArray javaClass JavaObject JavaPackage
- Windows Reserved Words
- alert all anchor anchors area
- assign blur button checkbox clearInterval
- clearTimeout clientInformation close closed confirm
- constructor crypto decodeURI decodeURIComponent defaultStatus
- document element elements embed embeds
- encodeURI encodeURIComponent escape event fileUpload
- focus form forms frame innerHeight
- innerWidth layer layers link location
- mimeTypes navigate navigator frames frameRate
- hidden history image images offscreenBuffering
- open opener option outerHeight outerWidth
- packages pageXOffset pageYOffset parent parseFloat
- parseInt password pkcs11 plugin prompt
- propertyIsEnum radio reset screenX screenY
- scroll secure select self setInterval
- setTimeout status submit taint text
- textarea top unescape untaint window
- JavaScript JSON
- JSON is a format for storing and transporting data.
- JSON is often used when data is sent from a server to a web page.
- What is JSON?
- SON stands for JavaScript Object Notation
- JSON is lightweight data interchange format
- JSON is language independent *
- JSON is "self-describing" and easy to understand
- ES6
-
BOM
-
JavaScript Window Screen
- The window.screen object contains information about the user's screen.
- screen.width
- screen.height
- screen.availWidth
- screen.availHeight
- screen.colorDepth
- screen.pixelDepth
-
JavaScript Window Location
- window.location.href returns the href (URL) of the current page
- window.location.hostname returns the domain name of the web host
- window.location.pathname returns the path and filename of the current page
- window.location.protocol returns the web protocol used (http:// or https://)
- window.location.assign loads a new document
- The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
-
JavaScript Window History
- The window.history object contains the browsers history.
- history.back() - same as clicking back in the browser
- history.forward() - same as clicking forward in the browser
-
JavaScript Window Navigator
- The window.navigator object contains information about the visitor's browser.
- navigator.appName
- navigator.appCodeName
- navigator.platform
-
JavaScript Popup Boxes
- JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
-
JavaScript Timing Events
- JavaScript can be executed in time-intervals.
- This is called timing events.
- Timing Events
- setTimeout(function, milliseconds)
- Executes a function, after waiting a specified number of milliseconds.
- setInterval(function, milliseconds)
- Same as setTimeout(), but repeats the execution of the function continuously.
-
JavaScript Cookies
- Cookies let you store user information in web pages.
- What are Cookies?
- Cookies are data, stored in small text files, on your computer.
- When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.
- Cookies were invented to solve the problem "how to remember information about the user":
- When a user visits a web page, his name can be stored in a cookie.
- Next time the user visits the page, the cookie "remembers" his name.
- Cookies are saved in name-value pairs like:
- Create a Cookie with JavaScript
- document.cookie = "username=John Doe";
- Read a Cookie with JavaScript
- var x = document.cookie;
- Change a Cookie with JavaScript
- document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
- Delete a Cookie with JavaScript
-
HTML
-
html5 tutorial
-
introduction
- 超文本标记语言: HyperText Markup Language
- <tagname attr>content</tagname>
-
editors
- notepad ,textEdit
-
elements
- opening tag+closing tag
- empty tag:br,hr(空元素在开始标签中关闭)
- <tagname>contents</tagname>
-
attributes
- html元素可以设置属性
- 属性可以在元素中添加附加信息
- 属性一般描述于开始标签
- 属性一般以字面量形式出现name='value'
- id,class,style,title,href,type,src,name,value,alt,disabled...
-
headings
- h1-h6:Headings Are Important
- Search engines use the headings to index the structure and content of your web pages.
Users skim your pages by its headings. It is important to use headings to show the document structure.
- hr:Defines a thematic change in the content
- 注释:<!--...-->
-
paragraphs
- Note: Browsers automatically add some white space (a margin) before and after a paragraph.
- br:The HTML <br> element defines a line break.
-
styles
- syntax:<tagname style="property:value;">
-
formatting
- b:bold
- strong:important
- i:italic
- em:emphasized
- mark:marked
- small:small
- del:deleted
- ins:inserted
- sub:subscript
- sup:superscript
-
quotations
- q:for short quotations
- blockquote:for quotations
- abbr:for abbreviations
- address:for contact information
- cit:for work title
- bdo:for bi-directional override(书写顺序)
-
computercode
- kbd:defines keyboard input
- samp:for computer output(计算输出)
- code:for computer code
- var :for variables
- pre:defines preformatted text
- commens
-
colors
- color names
- rgb value
- rgba
- hex
-
styles-css
- CSS stands for Cascading Style Sheets.CSS describes how HTML elements are to be displayed on screen, paper, or in other media.
CSS saves a lot of work. It can control the layout of multiple web pages all at once.
- CSS can be added to HTML elements in 3 ways:
Inline - by using the style attribute in HTML elements
Internal - by using a <style> element in the <head> section
External - by using an external CSS file
-
links
- A link does not have to be text. It can be an image or any other HTML element.
- HTML Links - The target Attribute
The target attribute specifies where to open the linked document.
The target attribute can have one of the following values:
_blank - Opens the linked document in a new window or tab
_self - Opens the linked document in the same window/tab as it was clicked (this is default)
_parent - Opens the linked document in the parent frame
_top - Opens the linked document in the full body of the window
framename - Opens the linked document in a named frame
-
images
- HTML Images Syntax:In HTML, images are defined with the <img> tag.
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
- The alt Attribute
The alt attribute provides an alternate text for an image, if the user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader).
If a browser cannot find an image, it will display the value of the alt attribute:
- Image Size - Width and Height
You can use the style attribute to specify the width and height of an image.Note: Always specify the width and height of an image. If width and height are not specified, the page will flicker(抖动) while the image loads.
- Width and Height, or Style?
Both the width, height, and style attributes are valid in HTML5.
However, we suggest using the style attribute(推荐用style). It prevents internal or external styles sheets from changing the original size of images:
- Image Floating
Use the CSS float property to let the image float to the right or to the left of a text:
- Image Maps
Use the <map> tag to define an image-map. An image-map is an image with clickable areas.
The name attribute of the <map> tag is associated with the <img>'s usemap attribute and creates a relationship between the image and the map.
The <map> tag contains a number of <area> tags, that defines the clickable areas in the image-map:
-
tables
- table>tr>th*m+tr>td*m------Note: The <td> elements are the data containers of the table.They can contain all sorts of HTML elements; text, images, lists, other tables, etc.
- HTML Table - Adding a Border
If you do not specify a border for the table, it will be displayed without borders.
A border is set using the CSS border property:table, th, td {
border: 1px solid black;
}Remember to define borders for both the table and the table cells.
- HTML Table - Collapsed Borders
If you want the borders to collapse into one border, add the CSS border-collapse property:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
- HTML Table - Adding Cell Padding
Cell padding specifies the space between the cell content and its borders.
If you do not specify a padding, the table cells will be displayed without padding.
To set the padding, use the CSS padding property:
Example
th, td {
padding: 15px;
}
- HTML Table - Left-align Headings
By default, table headings are bold and centered.
To left-align the table headings, use the CSS text-align property:
Example
th {
text-align: left;
}
- HTML Table - Adding Border Spacing
Border spacing specifies the space between the cells.
To set the border spacing for a table, use the CSS border-spacing property:
Example
table {
border-spacing: 5px;
}
- HTML Table - Cells that Span Many Columns
To make a cell span more than one column, use the colspan attribute:HTML Table - Cells that Span Many Rows
To make a cell span more than one row, use the rowspan attribute:
- HTML Table - Adding a Caption
To add a caption to a table, use the <caption> tag:The <caption> tag must be inserted immediately after the <table> tag.
- A Special Style for One Table
To define a special style for a special table, add an id attribute to the table:table#t01 {
width: 100%;
background-color: #f1f1c1;
}
- links
- 子主题 1
- 子主题 2
- 子主题 3
- 子主题 4
- 子主题 5
-
lists
- Unordered HTML List
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items will be marked with bullets (small black circles) by default:
- Unordered HTML List - Choose List Item Marker
The CSS list-style-type property is used to define the style of the list item marker:
Value Description
disc Sets the list item marker to a bullet (default)
circle Sets the list item marker to a circle
square Sets the list item marker to a square
none The list items will not be marked
- Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:
- Ordered HTML List - The Type Attribute
The type attribute of the <ol> tag, defines the type of the list item marker:
Type Description
type="1" The list items will be numbered with numbers (default)
type="A" The list items will be numbered with uppercase letters
type="a" The list items will be numbered with lowercase letters
type="I" The list items will be numbered with uppercase roman numbers
type="i" The list items will be numbered with lowercase roman numbers
- HTML Description Lists
HTML also supports description lists.
A description list is a list of terms, with a description of each term.
The <dl> tag defines the description list, the <dt> tag defines the term (name), and the <dd> tag describes each term:
- Nested HTML Lists
List can be nested (lists inside lists):Note: List items can contain new list, and other HTML elements, like images and links, etc.
- 子主题 7
-
blocks
- HTML Block and Inline Elements
Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is block or inline.
- Block-level Elements:A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
- div
- p
- h1-h6
- form
- ul,ol,dl,li
- table,tr,th
- hr,br,
- 子主题 8
- inline elements:An inline element does not start on a new line and only takes up as much width as necessary.
- span,i,em,b,strong,
- img,a
- code,kbd
- 子主题 4
-
classes
- 子主题 1
- 子主题 2
- 子主题 3
- 子主题 4
- iframes
- js
-
head
- The HTML <head> Element
The <head> element is a container for metadata (data about data) and is placed between the <html> tag and the <body> tag.
HTML metadata is data about the HTML document. Metadata is not displayed.
Metadata typically define the document title, character set, styles, links, scripts, and other meta information.
The following tags describe metadata: <title>, <style>, <meta>, <link>, <script>, and <base>.
-
layout
- layout elements
- header
- nav
- section
- article
- aside
- footer
- <header> - Defines a header for a document or a section
<nav> - Defines a container for navigation links
<section> - Defines a section in a document
<article> - Defines an independent self-contained article
<aside> - Defines content aside from the content (like a sidebar)
<footer> - Defines a footer for a document or a section
<details> - Defines additional details
<summary> - Defines a heading for the <details> element
- HTML Layout Techniques
There are four different ways to create multicolumn layouts. Each way has its pros and cons:
HTML tables
CSS float property
CSS framework
CSS flexbox
- Do NOT use tables for your page layout!
- CSS Frameworks
If you want to create your layout fast, you can use a framework, like W3.CSS or Bootstrap.
- CSS Floats
It is common to do entire web layouts using the CSS float property. Float is easy to learn - you just need to remember how the float and clear properties work. Disadvantages: Floating elements are tied to the document flow, which may harm the flexibility. Learn more about float in our CSS Float and Clear chapter.
- CSS Flexbox
Flexbox is a new layout mode in CSS3.
Use of flexbox ensures that elements behave predictably when the page layout must accommodate different screen sizes and different display devices. Disadvantages: Does not work in IE10 and earlier.
Learn more about flexbox in our CSS Flexbox chapter.
- 子主题 7
- 子主题 8
-
responsive
- What is Responsive Web Design?
Responsive Web Design makes your web page look good on all devices (desktops, tablets, and phones).
Responsive Web Design is about using CSS and HTML to resize, hide, shrink, enlarge, or move the content to make it look good on any screen:
-
entities(实体)
-
Result Description Entity Name Entity Number
non-breaking space  
< less than < <
> greater than > >
& ampersand & &
" double quotation mark " "
' single quotation mark (apostrophe) ' '
¢ cent ¢ ¢
£ pound £ £
¥ yen ¥ ¥
€ euro € €
© copyright © ©
® registered trademark ® ®
Note: Entity names are case sensitive.
-
symbols
- 子主题 1
- 子主题 2
- 子主题 3
- 子主题 4
- charset:http://www.w3schools.com/html/html_charset.asp
- URL Encode:http://www.w3schools.com/html/html_urlencode.asp
- 子主题 29
-
html forms
-
forms
- The <form> Element
The HTML <form> element defines a form that is used to collect user input:
- The Action Attribute
The action attribute defines the action to be performed when the form is submitted.
Normally, the form data is sent to a web page on the server when the user clicks on the submit button.
In the example above, the form data is sent to a page on the server called "action_page.php". This page contains a server-side script that handles the form data:
<form action="action_page.php">
If the action attribute is omitted, the action is set to the current page.
- The Method Attribute
The method attribute specifies the HTTP method (GET or POST) to be used when submitting the form data:
<form action="action_page.php" method="get">
- When to Use GET?
The default method when submitting form data is GET.
However, when GET is used, the submitted form data will be visible in the page address field:
action_page.php?firstname=Mickey&lastname=Mouse
Note: GET must NOT be used when sending sensitive information! GET is best suited for short, non-sensitive, amounts of data, because it has size limitations too.
When to Use POST?
Always use POST if the form data contains sensitive or personal information. The POST method does not display the submitted form data in the page address field.
POST has no size limitations, and can be used to send large amounts of data.
- The Name Attribute
Each input field must have a name attribute to be submitted.
If the name attribute is omitted, the data of that input field will not be sent at all.
This example will only submit the "Last name" input field:
- Grouping Form Data with <fieldset>
The <fieldset> element is used to group related data in a form.
The <legend> element defines a caption for the <fieldset> element.
-
form elements
- input:type=xxx
- select>option*n
- textarea
- button
- datalist
- HTML5 <datalist> Element
The <datalist> element specifies a list of pre-defined options for an <input> element.
Users will see a drop-down list of the pre-defined options as they input data.
The list attribute of the <input> element, must refer to the id attribute of the <datalist> element.
OperaSafariChromeFirefoxInternet Explorer
Example
<form action="action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
- keygen
- The purpose of the <keygen> element is to provide a secure way to authenticate users
- output
- The <output> element represents the result of a calculation (like one performed by a script).
-
input types
- text
- radio
- checkbox
- email
- number
- file
- color
- range
- url
- search
- button
- time
- week
- month
- date
- datetime-local
- datetime
-
input attributes
- The value Attribute
The value attribute specifies the initial value for an input field:
- The readonly Attribute
The readonly attribute specifies that the input field is read only (cannot be changed):
Example
<form action="">
First name:<br>
<input type="text" name="firstname" value="John" readonly>
</form>
- The disabled Attribute
The disabled attribute specifies that the input field is disabled.
- The size Attribute
The size attribute specifies the size (in characters) for the input field:
Example
<form action="">
First name:<br>
<input type="text" name="firstname" value="John" size="40">
</form>
- The maxlength Attribute
The maxlength attribute specifies the maximum allowed length for the input field:
Example
<form action="">
First name:<br>
<input type="text" name="firstname" maxlength="10">
</form>
- The autocomplete Attribute
The autocomplete attribute specifies whether a form or input field should have autocomplete on or off.
- The novalidate Attribute
The novalidate attribute is a <form> attribute.
When present, novalidate specifies that the form data should not be validated when submitted.
OperaSafariChromeFirefoxInternet Explorer
Example
Indicates that the form is not to be validated on submit:
<form action="action_page.php" novalidate>
E-mail: <input type="email" name="user_email">
<input type="submit">
</form>
- The autofocus Attribute
The autofocus attribute specifies that the input field should automatically get focus when the page loads.
OperaSafariChromeFirefoxInternet Explorer
Example
Let the "First name" input field automatically get focus when the page loads:
First name:<input type="text" name="fname" autofocus>
- The form Attribute
The form attribute specifies one or more forms an <input> element belongs to.
Tip: To refer to more than one form, use a space-separated list of form ids.
OperaSafariChromeFirefoxInternet Explorer
Example
An input field located outside the HTML form (but still a part of the form):
<form action="action_page.php" id="form1">
First name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
</form>
Last name: <input type="text" name="lname" form="form1">
- The formaction Attribute
The formaction attribute specifies the URL of a file that will process the input control when the form is submitted.
The formaction attribute overrides the action attribute of the <form> element.
The formaction attribute is used with type="submit" and type="image".
- The formenctype Attribute
The formenctype attribute specifies how the form data should be encoded when submitted (only for forms with method="post").
- The formmethod Attribute
The formmethod attribute defines the HTTP method for sending form-data to the action URL.
- The list Attribute
The list attribute refers to a <datalist> element that contains pre-defined options for an <input> element.
OperaSafariChromeFirefoxInternet Explorer
Example
An <input> element with pre-defined values in a <datalist>:
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
- The min and max Attributes
The min and max attributes specify the minimum and maximum values for an <input> element.
- The multiple Attribute
The multiple attribute specifies that the user is allowed to enter more than one value in the <input> element.
The multiple attribute works with the following input types: email, and file.
- The pattern Attribute
The pattern attribute specifies a regular expression that the <input> element's value is checked against
- The placeholder Attribute
The placeholder attribute specifies a hint that describes the expected value of an input field (a sample value or a short description of the format).
- The required Attribute
- The step Attribute
-
html5
-
intro
- What is New in HTML5?
- <!DOCTYPE html>
- <meta charset="UTF-8">,The default character encoding in HTML5 is UTF-8.
- New HTML5 Elements
- New semantic elements like <header>, <footer>, <article>, and <section>.
- New attributes of form elements like number, date, time, calendar, and range.
- New graphic elements: <svg> and <canvas>.
- New multimedia elements: <audio> and <video>.
- New HTML5 API's (Application Programming Interfaces)
- HTML Geolocation
- HTML Drag and Drop
- HTML Local Storage
- Tip: HTML Local storage is a powerful replacement for cookies.
- HTML Application Cache
- HTML Web Workers
- HTML SSE
-
HTML5 Browser Support
- HTML5 Browser Support
HTML5 is supported in all modern browsers.
In addition, all browsers, old and new, automatically handle unrecognized elements as inline elements.
Because of this, you can "teach" older browsers to handle "unknown" HTML elements.
You can even teach IE6 (Windows XP 2001) how to handle unknown HTML elements.
- Define Semantic Elements as Block Elements
HTML5 defines eight new semantic elements. All these are block-level elements.
To secure correct behavior in older browsers, you can set the CSS display property for these HTML elements to block:
header, section, footer, aside, nav, main, article, figure {
display: block;
}
- Add New Elements to HTML
You can also add new elements to an HTML page with a browser trick.
This example adds a new element called <myHero> to an HTML page, and defines a style for it:<!DOCTYPE html>
<html>
<head>
<script>document.createElement("myHero")</script>
<style>
myHero {
display: block;
background-color: #dddddd;
padding: 50px;
font-size: 30px;
}
</style>
</head>
<body>
<h1>A Heading</h1>
<myHero>My Hero Element</myHero>
</body>
</html>
- Problem With Internet Explorer 8
You could use the solution described above for all new HTML5 elements.
However, IE8 (and earlier) does not allow styling of unknown elements!
Thankfully, Sjoerd Visscher created the HTML5Shiv! The HTML5Shiv is a JavaScript workaround to enable styling of HTML5 elements in versions of Internet Explorer prior to version 9.
You will require the HTML5shiv to provide compatibility for IE Browsers older than IE 9.
- Syntax For HTML5Shiv
The HTML5Shiv is placed within the <head> tag.
The HTML5Shiv is a javascript file that is referenced in a <script> tag.
You should use the HTML5Shiv when you are using the new HTML5 elements such as: <article>, <section>, <aside>, <nav>, <footer>.
-
New Elements in HTML5
- New Semantic/Structural Elements
- <article> Defines an article in the document
- <aside> Defines content aside from the page content
- <bdi> Defines a part of text that might be formatted in a different direction from other text
- <details> Defines additional details that the user can view or hide
- <dialog> Defines a dialog box or window
- <figcaption> Defines a caption for a <figure> element
- <figure> Defines self-contained content, like illustrations, diagrams, photos, code listings, etc.
- <footer> Defines a footer for the document or a section
- <header> Defines a header for the document or a section
- <main> Defines the main content of a document
- <mark> Defines marked or highlighted text
- <menuitem> Defines a command/menu item that the user can invoke from a popup menu
- <meter> Defines a scalar measurement within a known range (a gauge)
- <nav> Defines navigation links in the document
- <progress> Defines the progress of a task
- <rt> Defines an explanation/pronunciation of characters (for East Asian typography)
- <ruby> Defines a ruby annotation (for East Asian typography)
- <section> Defines a section in the document
- <summary> Defines a visible heading for a <details> element
- <time> Defines a date/time
- <wbr> Defines a possible line-break
- New Form Elements
- <datalist> Defines pre-defined options for input controls
- <keygen> Defines a key-pair generator field (for forms)
- <output> Defines the result of a calculation
- New Input Types
- New Input Types
- color
date
datetime
datetime-local
email
month
number
range
search
tel
time
url
week
- New Input Attributes
- autocomplete
autofocus
form
formaction
formenctype
formmethod
formnovalidate
formtarget
height and width
list
min and max
multiple
pattern (regexp)
placeholder
required
step
- HTML5 - New Attribute Syntax
- HTML5 allows four different syntaxes for attributes.
This example demonstrates the different syntaxes used in an <input> tag:
Type Example
Empty <input type="text" value="John" disabled>
Unquoted <input type="text" value=John>
Double-quoted <input type="text" value="John Doe">
Single-quoted <input type="text" value='John Doe'>
In HTML5, all four syntaxes may be used, depending on what is needed for the attribute.
- HTML5 Graphics
- <canvas> Draw graphics, on the fly, via scripting (usually JavaScript)
<svg> Draw scalable vector graphics
- New Media Elements
- <audio> Defines sound content
- <embed> Defines containers for external applications (like plug-ins)
- <source> Defines sources for <video> and <audio>
- <track> Defines tracks for <video> and <audio>
- <video> Defines video or movie content
- HTML5 Semantic Elements
- Semantic elements = elements with a meaning.
- HTML5 Migration
- You can migrate from XHTML to HTML5, using the same recipe.
- HTML5 Style Guide and Coding Conventions
- Always keep your code tidy, clean, and well-formed.
-
html graphics
-
canvas
- he HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
-
SVG
- What is SVG?
SVG stands for Scalable Vector Graphics
SVG is used to define graphics for the Web
SVG is a W3C recommendation
- <!DOCTYPE html>
<html>
<body>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
</body>
</html>
-
<svg width="400" height="100">
<rect width="400" height="100" style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" />
</svg>
- <svg width="400" height="180">
<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</svg>
- <svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>
-
<svg height="130" width="500">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="50" y="86">SVG</text>
Sorry, your browser does not support inline SVG.
</svg>
-
Canvas Resolution dependent
No support for event handlers
Poor text rendering capabilities
You can save the resulting image as .png or .jpg
Well suited for graphic-intensive games
SVG Resolution independent
Support for event handlers
Best suited for applications with large rendering areas (Google Maps)
Slow rendering if complex (anything that uses the DOM a lot will be slow)
Not suited for game applications
-
google Maps
- Google Maps allows you to display maps on your web page:
- <!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="map" style="width:400px;height:400px;background:yellow"></div>
<script>
function myMap() {
var mapOptions = {
center: new google.maps.LatLng(51.5, -0.12),
zoom: 10,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=myMap"></script>
</body>
</html>
-
html media
-
Media
- http://www.w3schools.com/html/html_media.asp
- Video
- Audio
- Plug-ins
- YouTube
-
H5 APIs
-
Geolocation
- Geolocation is most accurate for devices with GPS, like iPhone.
- <script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
- Drag/Drop
- Local Storage
- App Cache
-
Web Workers
- A web worker is a JavaScript running in the background, without affecting the performance of the page.
-
SSE
- Server-Sent Events allow a web page to get updates from a server.
-
三大(UI)库
-
jQuery
-
jQuery Tutorial
- jQuery greatly simplifies JavaScript programming.
- jQuery Get Started
-
jQuery Syntax
- With jQuery you select (query) HTML elements and perform "actions" on them.
- Basic syntax is: $(selector).action()
- The Document Ready Event
- Trying to hide an element that is not created yet
- Trying to get the size of an image that is not loaded yet
- This is to prevent any jQuery code from running before the document is finished loading (is ready).
- It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
-
jQuery Selectors
- Syntax Description Example
- $("*") Selects all elements Try it
- $(this) Selects the current HTML element Try it
- $("p.intro") Selects all <p> elements with class="intro" Try it
- $("p:first") Selects the first <p> element Try it
- $("ul li:first") Selects the first <li> element of the first <ul> Try it
- $("ul li:first-child") Selects the first <li> element of every <ul> Try it
- $("[href]") Selects all elements with an href attribute Try it
- $("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank" Try it
- $("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank" Try it
- $(":button") Selects all <button> elements and <input> elements of type="button" Try it
- $("tr:even") Selects all even <tr> elements Try it
- $("tr:odd") Selects all odd <tr> elements Try it
-
jQuery Event Methods
- jQuery is tailor-made to respond to events in an HTML page.
-
jQuery Effects
- jQuery Effects - Hide and Show
- jQuery Effects - Fading
- jQuery Effects - Sliding
- jQuery Effects - Animation
- jQuery Stop Animations
- jQuery - Chaining
-
jQuery HTML
-
jQuery - Get Content and Attributes
- Get Content - text(), html(), and val()
- Get Attributes - attr()
-
jQuery - Add Elements
- append() - Inserts content at the end of the selected elements
- prepend() - Inserts content at the beginning of the selected elements
- after() - Inserts content after the selected elements
- before() - Inserts content before the selected elements
-
jQuery - Remove Elements
- remove() - Removes the selected element (and its child elements)
- empty() - Removes the child elements from the selected element
-
jQuery - Get and Set CSS Classes
- addClass() - Adds one or more classes to the selected elements
- removeClass() - Removes one or more classes from the selected elements
- toggleClass() - Toggles between adding/removing classes from the selected elements
- css() - Sets or returns the style attribute
-
jQuery - Dimensions
- With jQuery, it is easy to work with the dimensions of elements and browser window.
- jQuery Dimension Methods
- width()
- height()
- innerWidth()
- innerHeight()
- outerWidth()
- outerHeight()
-
jQuery Traversing
- Traversing the DOM
-
jQuery Traversing - Ancestors
- parent()
- parents()
- parentsUntil()
-
jQuery Traversing - Descendants
- children()
- find()
-
jQuery Traversing - Siblings
- siblings()
- next()
- nextAll()
- nextUntil()
- prev()
- prevAll()
- prevUntil()
-
jQuery Traversing - Filtering
- jQuery first() Method
- jQuery last() Method
- jQuery eq() method
- jQuery filter() Method
- jQuery not() Method
-
jQuery AJAX
- AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
-
jQuery - AJAX load() Method
- $(selector).load(URL,data,callback);
- jQuery - AJAX get() and post() Methods
-
jQuery Misc
- jQuery - The noConflict() Method
-
Bootstrap
-
Bootstrap 3 Tutorial
-
Bootstrap Get Started
- What is Bootstrap?
- Bootstrap is a free front-end framework for faster and easier web development
- Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many other, as well as optional JavaScript plugins
- Bootstrap also gives you the ability to easily create responsive designs
-
Bootstrap Grids
- Grid Classes
- The Bootstrap grid system has four classes:
- xs (for phones)
- sm (for tablets)
- md (for desktops)
- lg (for larger desktops)
- Bootstrap Text/Typography
- Bootstrap Tables
- Bootstrap Images
- Bootstrap Jumbotron and Page Header
- Bootstrap Wells
- Bootstrap Alerts
- Bootstrap Buttons
- Bootstrap Button Groups
- Bootstrap Glyphicons
- Bootstrap Badges and Labels
- Bootstrap Progress Bars
- Bootstrap Pagination
- Bootstrap Pager
- Bootstrap List Groups
- Bootstrap Panels
- Bootstrap Dropdowns
- Bootstrap Collapse
- Bootstrap Tabs and Pills
- Bootstrap Navigation Bar
- Bootstrap Forms
- Bootstrap Form Inputs
- Bootstrap Form Inputs (more)
- Bootstrap Input Sizing
- Bootstrap Media Objects
- Bootstrap Carousel Plugin
- Bootstrap Modal Plugin
- Bootstrap Tooltip Plugin
- Bootstrap Popover Plugin
- Bootstrap Scrollspy Plugin (Advanced)
- Bootstrap Affix Plugin (Advanced)
-
Bootstrap Grid System
- Bootstrap Grid - Stacked-to-horizontal
- Bootstrap Grid - Small Devices
- Bootstrap Grid - Medium Devices
- Bootstrap Grid - Large Devices
-
Bootstrap Templates
- Bootstrap Theme "Simply Me"
- Bootstrap Theme "Company"
- Bootstrap Theme "The Band"
- mui
-
计算机知识储备
- 编译原理
- 计算机网络
- 软件工程/测试原理
-
版本控制
-
Git
-
git init(初始化)
- Directory(目录):A folder used for storing multiple files.
- Repository(存储库):A directory where Git has been initialized to start version controlling your files.
-
git status(检索状态)
- The .git directory: It's usually hidden but we're showing it to you for convenience. If you click it you'll notice it has all sorts of directories and files inside it. You'll rarely ever need to do anything inside here but it's the guts of Git, where all the magic happens.
- It's healthy to run git status often. Sometimes things change and you don't notice it.
-
git add xx.txt
- deleted: File has been deleted and is waiting to be removed from Git.
- untracked: Files aren't tracked by Git yet. This usually indicates a newly created file.
- staged(暂存): Files are ready to be committed.
- unstaged: Files with changes that have not been prepared to be committed.
-
git commit -m 'xxx'
- //Staging Area: A place where we can group files together before we "commit" them to Git. Commit A "commit" is a snapshot of our repository. This way if we ever need to look back at the changes we've made (or if someone else does), we will see a nice timeline of all changes.
-
git log
- git log
-
git remote add origin https://github.com/try-git/try_git.git
- //git remote: Git doesn't care what you name your remotes, but it's typical to name your main one origin. It's also a good idea for your main repository to be on a remote server like GitHub in case your machine is lost at sea during a transatlantic boat cruise or crushed by three monkey statues during an earthquake.
- 作者: 行云流水7
- 链接:http://www.imooc.com/article/14426
- 来源:慕课网
- 本文原创发布于慕课网 ,转载请注明出处,谢谢合作!
- git push -u origin master
- git pull origin master
- git diff HEAD
- git diff --staged
- git reset octofamily/octodog.txt
- git checkout --ocotcat.txt
- git branch clean_up
- git checkout clean_up
- git rm '*.txt'
- git checkout master
- git merge clean_up
- git branch -d clean_up
- git push
- SVN