CH1 Inet and WebBasics
1. Internet and Web Basics
-
The Internet: A global network of interconnected computers.
-
ARPAnet: The first version of the Internet, developed in 1969.
-
NSFnet: Expanded use beyond government and academic sectors after 1991.
2. The World Wide Web
-
A graphical interface to access Internet resources.
-
Evolved through the development of web browsers like Mosaic.
3. Web Standards and W3C
-
W3C (World Wide Web Consortium): Develops web standards and recommendations.
-
WAI (Web Accessibility Initiative): Ensures web accessibility for users with disabilities.
-
WCAG 2.0: Guidelines for creating accessible web content.
4. Universal Design
- Designing websites to be usable by everyone without special adaptation.
5. Networking Concepts
-
Network: Two or more connected computers sharing data.
-
Client/Server Model: Client (e.g., browser) sends requests, server responds.
6. Internet Protocols
-
TCP/IP: Core protocol for internet communication.
-
FTP: File Transfer Protocol.
-
SMTP, POP3, IMAP: Email protocols.
-
HTTP: Protocol for transferring web pages.
7. IP Addresses and Domain Names
-
IP Address: Numeric address of a device on the Internet.
-
Domain Name: Human-readable name (e.g., google.com) that maps to IP addresses.
-
DNS (Domain Name System): Translates domain names into IP addresses.
8. Uniform Resource Identifiers (URI)
-
URL (Uniform Resource Locator): Specifies the address of resources on the Internet.
-
TLDs (Top-Level Domains): Includes .com, .edu, .gov, etc.
-
New gTLDs: Recently added like .guru, .bike.
-
Country Code TLDs: Two-letter codes like .uk, .jp.
9. Markup Languages
-
SGML: Standard Generalized Markup Language (parent of HTML/XML).
-
HTML: Markup language for structuring web content.
-
XML: Used for structured data exchange.
-
XHTML: Combines HTML and XML features.
-
HTML5: Latest version with enhanced multimedia and structural capabilities.
10. Creating a Basic HTML5 Web Page
-
Key elements:
<html>
,<head>
,<title>
,<meta>
,<body>
-
No need for DTD in HTML5.
-
Structure and syntax basics for writing your first web page.
CH2 HTML Basics
1.Text Formatting Elements
-
Headings :
<h1>
to<h6>
for section titles -
Paragraphs :
<p>
to group text into blocks -
Line breaks :
<br>
starts a new line (void element) -
Horizontal rules :
<hr>
draws a thematic break line
2.Phrase Elements (Inline)
-
<b>
: bold text -
<strong>
: important text (semantic bold) -
<i>
: italic text -
<em>
: emphasized text (semantic italic)
3. HTML Lists
-
Unordered list :
<ul>
+<li>
(bullet points) -
Ordered list :
<ol>
+<li>
(numbered items) -
Description list :
<dl>
+<dt>
(term) +<dd>
(description)
4.Special Characters
Use entity codes to display reserved or special characters:
-
©
→ © -
<
→ < -
>
→ > -
→ (non-breaking space)
5.Div Element
-
<div>
is a general-purpose block container -
Used to group content, apply styles, or manipulate sections with JavaScript
-
Not semantic, but very flexible
6.HTML5 Structural Elements
-
<header>
: contains headings or logo -
<nav>
: navigation menu -
<main>
: main content area -
<footer>
: page footer
7.Anchor Element and Hyperlinks
-
<a href="URL">Link Text</a>
: creates hyperlinks -
Absolute links : go to external sites (e.g.,
http://google.com
) -
Relative links : link to pages on the same site (e.g.,
about.html
) -
Email links :
mailto:example@example.com
-
Open in new tab : add
target="_blank"
8.HTML Validation
-
Ensures clean, correct code for consistent browser display
-
Use tools like:
CH3 WebDesign Basic
1.Website Organization Models
-
Hierarchical: A main homepage with links to sections; common in corporate websites.
-
Linear: Pages in a sequence (like tutorials).
-
Random (Web): No clear path; often for artistic or experimental sites.
Tips : Avoid too shallow (too many links) or too deep (too many clicks) structures. Use the "Three-Click Rule" for better user experience.
2.Visual Design Principles
-
Repetition: Repeat visual elements for unity
-
Contrast: Make important elements stand out
-
Proximity: Group related items
-
Alignment: Visually connect elements for structure
3.Accessibility Design
-
Based on WCAG 2.0 with the POUR principles:
-
Perceivable
-
Operable
-
Understandable
-
Robust
-
-
Use ARIA (Accessible Rich Internet Applications) attributes for screen reader support.
4.Search Engine Optimization (SEO)
On-page SEO elements:
-
Keywords
-
High-quality content
-
Title tags & meta descriptions
-
Headings (H1, H2, etc.)
-
Internal linking
-
Image alt text
-
Clean URL structure
5.Writing for the Web
-
Use short paragraphs, bullet points, and subheadings
-
Use common fonts (e.g., Arial, Verdana)
-
Use good contrast between text and background
-
Avoid long horizontal lines of text
6.Color Theory in Design
-
Color harmony types:
-
Monochromatic
-
Analogous
-
Complementary
-
Triadic
-
Tetradic
-
Split complementary
-
-
Color psychology:
-
Red = energy, urgency
-
Blue = trust, professionalism
-
Green = health, nature
-
Yellow = optimism
-
Black = elegance
-
7.Graphics and Multimedia
-
Use optimized images to reduce load time
-
Always include alt text for accessibility
-
Limit unnecessary multimedia
-
Avoid very large graphics; keep homepage under 60KB
8.Page Layout and Wireframes
-
Use white space and columns to make layouts easier to read
-
Design with:
-
Fixed layout: fixed width (e.g., 960px)
-
Fluid layout: percentage-based, adapts to browser size
-
Responsive design: adapts to mobile using media queries
-
9.Mobile Design Principles
-
Single-column layout
-
High contrast
-
Image and bandwidth optimization
-
Avoid non-essential content
10.Navigation Design
-
Consistent placement (usually top or left)
-
Use navigation bars, breadcrumbs, and search
-
Include "Skip to Content" links for accessibility
11.Web Design Best Practices Checklist
Evaluate your design for:
-
Layout
-
Browser compatibility
-
Navigation
-
Color/graphics
-
Content
-
Accessibility
-
Load time
CH4 CSS Basics
Typography
font-family: Specifies the typeface.
font-size: Sets the size of the text.
line-height: Controls the spacing between lines.
letter-spacing: Adjusts the space between characters.
text-align: Aligns text (left, right, center, justify).
font-weight: Sets the thickness of the text (e.g., bold, normal).
Cascading Style Sheets (CSS)
Inline Styles
- bodysection
- HTML styleattribute
- apply only to the specific element
<p style="color: #666; font-size: 16px; line-height: 1.5;">
This is an example of inline styles in action.
</p>
Embedded Styles
- headsection
- HTML style element
- apply to the entire web page document
External Styles
- Separate text file with**.css file**extension
- Associate with a HTML link element in the head section of a web page
<link rel="stylesheet" href="color.css">
Imported Styles
- Similar to External Styles
- We'll concentrate on theother three types of styles.
CSS Syntax

Selector { Declaration Property : Declaration Value }
Configuring Text with CSS
font-weight:Configures the boldness of text
font-style:Configures text to an italic style
font-size:Configures the size of the text
font-family:Configures the font typeface of the text
More CSS TEXT Properties
line-height:Configures the height of the line of text (use the value 200% to appear double-spaced)
text-align:Configures alignment of text within a block display element
text-indent:Configures the indentation of the first line of text
text-decoration:Modifies the appearance of text with an underline, overline, or line-through text-transform Configures the capitalization of text
text-shadow:Configures a drop shadow on text
Basic Selectors
Element Selector: Syntax: element
Example: p { color: blue; }
Class Selector: Syntax: .classname
Example: .highlight { background-color: yellow; }
ID Selector: Syntax: #idname
Example: #header { font-size: 24px; }
Universal Selector: Syntax: *
Example: * { margin: 0; padding: 0; }
Attribute Selectors
Attribute Presence: Syntax: [attribute]
Example: [target] { border: 1px solid black; }
Attribute Value: Syntax: [attribute="value"]
Example: [type="submit"] { background-color: green; }
Attribute Contains: Syntax: [attribute*="value"]
Example: [href*="example"] { color: red; }
Attribute Starts With: Syntax: [attribute^="value"]
Example: [href^="https"] { color: green; }
Attribute Ends With: Syntax: [attribute$="value"]
Example: [href$=".pdf"] { color: blue; }
Combinators
Descendant Combinator: Syntax: selector1 selector2
Example: div p { color: red; }
所有在 div
里面的 p
标签都会变红,包括嵌套很多层的 p
。
选择所有在 selector1
元素内部的 selector2
元素,不管相隔多少层。
Child Combinator: Syntax: selector1 > selector2
Example: ul > li { list-style-type: square; }
只会选中 ul
下直接的 li
子元素,深层嵌套的 li
不会被选中。
只选择作为 selector1
直接子元素 的 selector2
。
Adjacent Sibling Combinator: Syntax: selector1 + selector2
Example: h1 + p { font-weight: bold; }
如果一个 p
紧跟在 h1
后面,它就会变成加粗。
选择紧跟在 selector1
后面的相邻的兄弟 selector2
元素(只能是一个)
General Sibling Combinator: Syntax: selector1 ~ selector2
Example: h1 ~ p { color: blue; }
所有在同一个父元素下,出现在 h1
后面的所有 p
标签都会变蓝。
选择所有在 selector1
后面的 selector2
兄弟元素(不一定相邻)。
Pseudo-Classes
伪类 :选中元素处于某种状态 或特定位置时的样式。
State-Based: Syntax: selector: pseudo-class
Example: a:hover { color: red; }
Position-Based: Syntax: selector: pseudo-class
Example: li:first-child { font-weight: bold; }
伪类 | 作用 |
---|---|
:hover |
当用户把鼠标悬停在元素上 |
:focus |
当元素获得焦点(如表单输入框) |
:first-child |
是其父元素的第一个子元素 |
:nth-child(n) |
是其父元素的第 n 个子元素 |
Pseudo-classes and the anchor element
link-- default state for a hyperlink
visited-- a hyperlink that has been visited
focus -- triggered when the hyperlink has focus
hover-- triggered when the mouse moves over the hyperlink
active -- triggered when the hyperlink is being clicked
Pseudo-Elements
伪元素 :选中元素内部的某个部分 ,或者在元素前后生成内容。
Content: Syntax: selector::pseudo-element
Examples: p::first-line { font-weight: bold; } p::before { content: "→ "; }
伪元素 | 作用 |
---|---|
::before |
在元素开始之前插入内容 |
::after |
在元素结尾之后插入内容 |
::first-line |
选中文本的第一行 |
::first-letter |
选中第一个字母 |
The "Cascade"
Brower Defaults -> External Styles -> Embedded Styles -> Inline Styles -> HTML Attributes
Overriding Rules
!important
无论选择器多么弱,只要你用了
!important
,就会覆盖其他样式。p {
color: red**!important** ;
}
哪怕别的地方写了
color: blue;
,也会被红色覆盖。
Inline styles
直接写在 HTML 标签中的
style
属性,比大多数 CSS 规则都强。<p style="color: green;">Hello</p>
即使外部样式表中写了
p { color: blue; }
,也会被行内的绿色覆盖(除非被!important
覆盖)。
ID selectors
用
#id
选中元素,优先级比类和标签高。#title {
font-size: 24px;
}
Class/attribute/pseudo-class selectors
类、属性、伪类选择器
使用
.class
、[type="text"]
、:hover
等,优先级中等。.highlight {
background-color: yellow;
}
input[type="text"] {
border: 1px solid black;
}
a:hover {
color: red;
}
Element/pseudo-element selectors
直接使用标签名(如
div
,p
)或伪元素(如::before
,::first-line
)选择的优先级比较低。p {
font-family: Arial;
}
p::first-letter {
font-size: 200%;
}
Source order (later rules override earlier ones)
同一优先级 时,靠后的规则会覆盖前面的。
p {
color: blue;
}
p {
color: orange;
}
color: orange;
生效,因为它写在后面。
Inherited styles
从父元素继承来的样式(如字体、颜色)最容易被覆盖。
<div style="color: gray;">
<p>这段文字颜色是继承来的</p>
</div>
!important
最大牌,行内样式紧跟来;ID 高于类与伪,标签伪元次一排;同级后写把前盖,继承样式最容易改。
CH5 Graphics and text Styling
The Box Model

CSS border Property
border-width border-style border-color
h2 { border: 2px solid #ff0000 }
border-style property
|------------|---------------------------------------------------------|-----------------------|
| Value | Description | Example |
| none | No border (default). | border-style: none; |
| hidden | Same as none, but still affects table border conflicts. | border-style: hidden; |
| solid | A single solid line. | border-style: solid; |
| dotted | A series of round dots. | border-style: dotted; |
| dashed | A series of short dashes. | border-style: dashed; |
| double | Two parallel solid lines. | border-style: double; |
| groove | 3D grooved effect (depends on border-color). | border-style: groove; |
| ridge | 3D ridged effect (opposite of groove). | border-style: ridge; |
| inset | Makes the element appear embedded. | border-style: inset; |
| outset | Makes the element appear raised. | border-style: outset; |
CSS Borders: Block / Inline Elements
Block display element
Default width of element content extends to browser margin (or specified width)
块级元素 (如:
div
,p
,h1
,ul
等)默认是占据一整行的宽度。如果没有设置
width
,它的宽度默认会自动延伸到父容器(或浏览器窗口)的边缘。所以当你对块级元素设置
border
,边框会围绕整块宽度展开。
Inline display element
Border closely outlines the element content
行内元素 (如:
span
,a
,strong
,em
等)只占据它内容所需的宽度。它不会自动扩展到整行。
所以当你对行内元素设置
border
,边框会紧紧包住文字或内容,就像给内容"贴了个标签"一样。
Block-Level Elements (display: block)
Behavior:
- Starts on a new line (takes full width by default).
- Stretches horizontally to fill the entire parent container.
- Can set width, height, margins, and padding (all sides).
- Can contain other block & inline elements.
- For Example: <div>, <p>, <h1>-<h6>, <section>, <article>, <ul>, <li>, <footer>, <header> etc
会另起一行开始显示(一个块级元素下面,另一个就自动换行)
默认占满整行宽度(就算内容很少,它的宽度也是整行)
可以设置宽度、高度、内外边距(margin 和 padding)
可以嵌套其他块级或行内元素
Inline Elements (display: inline)
Behavior:
- Does NOT start a new line (flows within text/content).
- Takes only the space needed for its content.
- Ignores width, height, and vertical margins (only left/right margins work).
- Padding works but may overlap other elements.
- Examples: <span>, <a>, <strong>, <em>, <img>, <br>, <button>, <input>
不会换行,和文字一起"流动"
只占用内容本身所需的宽度
不能设置宽度/高度,也不能使用上下外边距(margin-top / margin-bottom)
padding 虽然有效,但上下 padding 不会撑开其他元素,可能会重叠
Hybrid: inline-block (display: inline-block)
- Flows like inline (no forced line breaks).
- Accepts width, height, margins, padding like block.
- Example: <button style="display: inline-block; width: 100px;">Click</button>
表现像行内元素(不会强制换行)
但可以像块级元素那样设置宽度、高度、margin、padding
适合做按钮、图片容器等既不想换行又想自定义大小的组件
|------------------|-----------------------------|--------------------------------------|
| Feature | Block Elements | Inline Elements |
| Line Break | Starts on a new line | Stays in the same line |
| Width | Full parent width (default) | Only as wide as content |
| Height/Width | Can be set | Ignored (naturally sized) |
| Margins | Works on all sides | Only left/right margins apply |
| Nesting | Can contain block & inline | Usually only text & inline elements |
Two numeric values or percentages
first value configures top and bottom padding
the second value configuresleft and rightpadding
Four numeric values or percentages
Configure top, right, bottom, and left padding
PNG:Combines the best of GIF & JPEG
HTML Image Element <IMG>
<img src="dog.jpg" alt="Dog at computer" height="100" width="100">
- src Attribute:File name of the graphic
- alt Attribute:Configures alternate text description
- height Attribute:Height of the graphic in pixels
- width Attribute:Width of the graphic in pixels
To Create Image Link
<a href="index.html"><img src="home.gif" height="19" width="85" alt="Home"></a>
HTML5 Meter Element
<meter value="XX" min="XX" max="XX">
<meter value="2062" min="0" max="14417">2062</meter> 2,062 Chrome<br>
HTML5 Progress Element
Displays a bar that depicts a numeric value within a specified range
<progress value="5000" max="10000">5000</progress>
CSS background-image Property
body { background-image: url(background1.gif); }
CSS3 Multiple Background Images
-
no-repeat
:不重复 -
repeat
:平铺整个页面
body {
color: #333333;
background-color: #f4ffe4;
background-image:
url(trilliumfoot.gif), /* Layer 1 (最上层背景图) */
url(trilliumgradient.png); /* Layer 2 (底层背景图) */
background-position: bottom right, center;
background-repeat: no-repeat, repeat;
背景底色是淡绿色。
页面底层是平铺的渐变背景图(
trilliumgradient.png
)。页面右下角叠加一张小图(
trilliumfoot.gif
),不重复。文字颜色是深灰。
HTML <map> Element
什么是 <map>
和 :
把一张图分成多个区域,每个区域都能点进去跳转到不同链接。
<img src="world-map.jpg" alt="World Map" usemap="#worldmap">
<map name="worldmap">
<area ...>
<area ...>
</map>
usemap="#worldmap"
表示这张图用一个叫 worldmap
的地图区域规则。
name="worldmap"
要和 usemap="#worldmap"
对应上(注意:usemap
里有 #
,name
里不要)。
(1)shape="rect"
------矩形区域
<area
shape="rect"
coords="34,44,270,350"
href="europe.html"
alt="Europe">
shape="rect"
:矩形
coords="34,44,270,350"
:左上角 (34, 44),右下角 (270, 350)
href="europe.html"
:点击这个区域会跳到europe.html
alt="Europe"
:无障碍辅助信息,告诉读屏软件这里是欧洲
(2)shape="circle"
------圆形区域
<area
shape="circle"
coords="500,200,50"
href="asia.html"
alt="Asia">
shape="circle"
:圆
coords="500,200,50"
:圆心是 (500, 200),半径是 50 像素其他含义类似上面
属性 | 出现位置 | 作用 |
---|---|---|
name |
<map> |
地图的名字,<img> 用 usemap="#这个名字" 连接 |
shape |
<area> |
点击区域的形状(rect 矩形、circle 圆形、poly 多边形) |
coords |
<area> |
坐标,用来定义这个形状在哪(不同形状坐标格式不同) |
href |
<area> |
你点击这个区域后跳转的网址 |
alt |
<area> |
区域的说明文字(用于辅助工具) |
|------------------------------------|-------------------------------------------------|--------------------------------------------|
| Shape | coords Format | Example |
| ++Rectangle++ (rect) | x1,y1,x2,y2 (top-left and bottom-right corners) | coords="34,44,270,350" |
| ++Circle++ (circle) | x,y,radius (center point + radius) | coords="500,200,50" |
| ++Polygon++ (poly) | x1,y1,x2,y2,...,xn,yn (vertices of the shape) | coords="100,100,200,50,300,100" (triangle) |
| ++Defa++ ++ult++ (default) | Covers the entire image (no coords needed) | shape="default" |
Favorites Icon - favicon
<link rel="icon" href="favicon.ico" type="image/x-icon">
CSS Sprites
Sprite -- an image file that contains multiple small graphics that are configured as background images for various web page elements.
Sprite(雪碧图)是一张大图,里面包含了很多小图标(比如按钮、图标、图标文字等),这些小图会分别被作为网页中不同部分的背景图来用。
假设我们有这样一张雪碧图 icons.png
:
它是一张 64px 高、横向排列的图片,包含三个图标,每个图标宽高是 32x32
像素:
| icon-home | icon-search | icon-user |
| 0px | -32px | -64px |
HTML 示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Sprite Example</title>
<style>
.icon {
display: inline-block;
width: 32px;
height: 32px;
background-image: url('icons.png'); /* 雪碧图 */
background-repeat: no-repeat;
}
.icon-home {
background-position: 0 0; /* x y */
}
.icon-search {
background-position: -32px 0;
}
.icon-user {
background-position: -64px 0;
}
</style>
</head>
<body>
<div class="icon icon-home" title="Home"></div>
<div class="icon icon-search" title="Search"></div>
<div class="icon icon-user" title="User"></div>
</body>
</html>
CSS3 Rounded Corners
h1 { border-radius: 15px; }
border-radius: 15px 30px 100px 5px;
top left, top right, bottom right, bottom left
CSS3 box-shadow Property
#wrapper { box-shadow: 5px 5px 5px #828282; }
the horizontal offset, vertical offset, blur radius, and valid color value
CSS3 opacity Property
h1{ background-color: #FFFFFF; opacity: 0.6; }
- 0 Completely Transparent
- 1 Completely Opaque
Rgba Color
h1 { color: #ffffff;
color: rgba(255, 255, 255, 0.7);
font-size: 5em; padding-right: 10px;
text-align: right;
font-family: Verdana, Helvetica, sans-serif;
}
red color, green color, blue color, and alpha(transparency)
- The values for red, green, and blue must be decimal values from 0 to 255.
- The alpha value must be a number between 0 (transparent) and 1 (opaque).
HSLA Color
- Hue is a value between 0 and 360
- Saturation: percent
- Lightness: percent
- Optional alpha: from 0 to 1
CSS3 Gradients
body {
background-color: #8FA5CE;
background-image: linear-gradient(#FFFFFF, #8FA5CE);
}
Gradient: a smooth blending of shades from one color to another
Use thebackground-image property
- linear-gradient()
- radial-gradient()
CH6 More CSS
The CSS box-sizing Property
The main values are content-box and border-box . content-box is the default.
<div class="box content-box">Content-Box (Wider)</div>
<div class="box border-box">Border-Box (Fixed Width)</div>
<style>
.box {
width: 200px;
padding: 20px;
border: 5px solid #333;
margin: 10px;
}
.content-box { box-sizing: content-box; } /* Total width: 250px */
.border-box { box-sizing: border-box; } /* Total width: 200px */
</style>
.border-box { box-sizing: border-box; }
这个class="box border-box"的box-sizing使用border-box,即box中的width指(content+padding+border),即总体的宽度就是200px
.content-box { box-sizing: content-box; }
这个class="box content-box"的box-sizing使用content-box,即box中的width指(只有content),即总体的宽度就是200px+20px*2+5px*2=250px
(都不用算margin)
float Property
The float property in CSS is used to position an element to the left or right of its container, allowing other content (like text or inline elements) to wrap around it.
It was historically used for page layouts but is now primarily used for text wrapping around images or small components.
#yls {
float: right;
margin: 0 0 5px 5px;
border: 1px solid #000000;
}
例子:
<h1>浮动示例</h1>
<img id="yls" src="cat.jpg" alt="小猫" width="150">
<p>
这是一段文字,会环绕图片显示。CSS 中的 float 属性可以让图像靠边显示,文字自动绕过图像排列。这种布局方式在文章排版中非常常见。
</p>
效果是:
-
cat.jpg
图片浮动在右边 -
段落文字环绕在图片左侧
-
图片有边框和间距,看起来更整齐
Modern Alternatives:
Flexbox: For 1D layouts (rows/columns).
只在一个方向上排元素 :横向(row) 或 纵向(column)
<div style="display: flex;">
<div>🍎</div>
<div>🍊</div>
<div>🍇</div>
</div>
元素只是在 横向(row)一条线上排列 ,就是1D 布局
CSS Grid: For 2D layouts.
可以同时控制行和列(横 + 纵)
<div style="display: grid; grid-template-columns: repeat(3, 1fr);">
<div>1️⃣</div>
<div>2️⃣</div>
<div>3️⃣</div>
<div>4️⃣</div>
<div>5️⃣</div>
<div>6️⃣</div>
</div>
这就是一个3 列、2 行的网格 ,同时控制了横和纵,是2D 布局
display: inline-block: For inline elements with controlled spacing.
它本质还是1D布局 ,因为元素只能横向排列 ,换行的话不能精细控制行列。spacing 间距需要自己处理(比如
font-size
间隙、white-space
)
Clear Property
- Useful to "clear" or terminate a float
- Values are left, right, and both
Overflow Property
- Intended to configure the display of elements on a Web page.
- However, it is useful to "clear" or terminate a float before the end of a container element
- Values are auto, hidden, and scroll
CSS display Property
Configures how and if an element is displayed
display: none;
The element will not be displayed.
display: block;
The element is rendered as a block element -- even if it is actually an inline element, such as a hyperlink.
display: inline;
The element will be rendered as an inline element -- even if it is actually a block element -- such as a <li>.
display: inline-block;
The element will display as an inline display element adjacent to other inline display elements but also can be configured with properties of block display elements including width and height.
Basic Two-Column Layout
#wrapper { width: 80%;
margin-left: auto;
margin-right: auto;
background-color: #EAEAEA; }
header { background-color: #CCCCFF; }
h1 { margin: 0; padding: 10px; }
nav { float: left;
width: 90px;
padding: 10px; }
main { margin-left: 100px;
padding: 10px;
background-color: #FFFFFF; }
footer { text-align: center;
font-style: italic;
background-color: #CCCCFF; }

<body>
<div id="wrapper">
<header> <header>
<nav> </nav>
<main> </main>
<footer> </footer>
</div>
</body>
Vertical navigation
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="menu.html">Menu</a></li>
<li><a href="directions.html">Directions</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
CSS removes the list marker and underline:
nav ul {list-style-type: none; }
nav a { text-decoration: none; }
Horizontal Navigation
CSS removes the list marker, removes the underline, adds padding, and configures the list items for inline display.
nav ul { list-style-type: none;}
nav a { text-decoration: none; padding-right: 10px; }
nav li { display: inline; }
Position Property
1. Relative Positioning
Behavior: Positions an element relative to its normal position in the document flow.
Key Characteristics:
- Doesn't remove the element from normal flow
- Creates a new stacking context
- Serves as a container for absolutely positioned children
Changes the location of an element in relation to where it would otherwise appear in normal flow
2. Absolute Positioning
Behavior: Removes element from normal flow and positions it relative to its nearest positioned ancestor (or the document if none exists).
Key Characteristics:
- Doesn't affect other elements' layout
- Requires explicit width (unless stretching with left/right)
- Can overlap other content
Precisely specifies the location of an element outside of normal flow in relation to its first parent non-static element
3. Fixed Positioning
Behavior: Positions element relative to the viewport (Browser Window).
Key Characteristics:
- Stays in same place during scrolling
- Removes element from normal document flow
- Useful for headers, footers, or modals

CH7 Page Layout
Landmark Roles with ARIA
Accessible Rich Internet Applications (ARIA)
Landmark Roles
- banner (a header/logo area)
- navigation (a collection of navigation elements)
- main (the main content of a document)
- complementary (a supporting part of the web page document, designed to be complementary to the main content )
- contentinfo (an area that contains information about the content such as copyright )
- form (an area that contains a form)
- search (an area of a web page that provides search functionality)
<body>
<div role="banner">
<h1>My Website</h1>
<nav role="navigation" aria-label="Main Menu">...</nav>
</div>
<div role="main">
<article>...</article>
</div>
<aside role="complementary" aria-label="Related Links">...</aside>
<div role="contentinfo">
<p>© 2024 My Site</p>
</div>
</body>
Opening a Link in a New Browser Window
The target attribute on the anchor element opens a link in a new browser window or new browser tab.
<a href="http://yahoo.com" target="_blank">Yahoo!</a>
Three Column Layout
Left-column navigation
- float: left; width:150px;
Right-column content
- float: right; width: 200px;
Center column
- Uses the remaining screen room available room after the floating columns display
- margin: 0 210px 0 160px;
Footer -- clears the float
- clear: both;

Viewport Meta Tag
<meta name="viewport" content ="width =device-width, initial-scale=1.0">
部分 | 意义 |
---|---|
name="viewport" |
声明这是一段设置视口的代码 |
width=device-width |
页面宽度设置为设备的实际屏幕宽度 |
initial-scale=1.0 |
初始缩放比例为 1(即不放大、不缩小) |
CSS3 Media Queries
- Determines the capability of the mobile device, such as screen resolution
- Directs the browser to styles configured specifically for those capabilities
例子 :写在
<link>
标签中<link href="lighthousemobile.css" rel="stylesheet"
media="only all and (max-device-width: 480px)">
只有当设备最大宽度小于等于 480 像素 时(例如手机),才会加载
lighthousemobile.css
这个样式表。例子 2:写在 CSS 文件中
@media only all and (max-width: 768px) {
body {
font-size: 16px;
}
}
浏览器窗口宽度 ≤ 768px(比如手机或小平板)时,文字大小变为 16px。
Media Query 能让你根据不同设备屏幕宽度/分辨率 ,指定不同的样式,是制作响应式网页的关键工具。
条件 | 含义 |
---|---|
max-width: 768px |
浏览器宽度 ≤ 768 像素时 |
min-width: 1024px |
浏览器宽度 ≥ 1024 像素时 |
orientation: portrait |
设备竖屏状态 |
orientation: landscape |
设备横屏状态 |
Flexible Images
img { max-width: 100%; height: auto; }
Responsive Images HTML 5.1 Picture Element
响应式图片:让浏览器根据屏幕大小 ,自动加载合适大小的图片,提升速度 & 画质
方式一 :使用
<picture>
标签(推荐用法)<picture>
<source media="(min-width: 1200px)" srcset="large.jpg">
<source media="(min-width: 800px)" srcset="medium.jpg">
<source media="(min-width: 320px)" srcset="small.jpg">
<img src="fallback.jpg" alt="waterwheel">
</picture>
最后的
<img>
:是默认图像,如果<source>
都不匹配,就用它方式二 :使用
srcset
+sizes
(写在<img>
上)<img src="fallback.jpg" sizes="100vw" srcset="large.jpg 1200w, medium.jpg 800w, small.jpg 320w" alt="waterwheel">
srcset
:列出不同尺寸的图片
1200w/800w/320w
:表示图片的实际宽度
sizes="100vw"
:告诉浏览器"这个图会占整个视口宽度",然后浏览器自动选择最合适的一张图
src="fallback.jpg"
:默认显示的图像
屏幕宽度 | 加载的图片 |
---|---|
≥1200px | large.jpg |
800~1199px | medium.jpg |
320~799px | small.jpg |
无法判断 | fallback.jpg |
Using Flexbox
Configure a flexible container "flex container"
Configure the direction of the flex
Example:
#demo { display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row; }
Adjust the proportion of the "flex item" elements in the container
Example:
nav { -webkit-flex: 1; flex: 1; }
main { -webkit-flex: 7; flex:7; }
aside { -webkit-flex:2; flex: 2 }
-
flex: 1
是一个占比单位 -
总比例是
1 + 7 + 2 = 10
-
nav
占 10%(1/10) -
main
占 70%(7/10) -
aside
占 20%(2/10)
-
属性 | 含义 |
---|---|
display: flex; |
把这个元素变成"弹性容器"(flex container) |
flex-direction: row; |
元素按一行横着排列(默认方向) |
-webkit- 前缀 |
是为兼容老的浏览器(可以记住不影响理解) |
CH8 Table Basics
HTML Table Elements
<table> Element:Contains the table
**<tr>**Element:Contains a table row
<td> Element:Contains a table data cell
**<th>**Element:Contains a table header cell
<caption> Element:Configures a description of the table
<table border="1">
<caption>Birthday List</caption>
<tr>
<td>Name</td>
<td>Birthday</td>
</tr>
<tr>
<td>James</td>
<td>11/08</td>
</tr>
<tr>
<td>Karen</td>
<td>4/17</td>
</tr>
<tr>
<td>Sparky</td>
<td>11/28</td>
</tr>
</table>
border Attribute
- Optional
- border="1" Visible browser default border.
- border="" No visible browser default border.
colspan Attribute
<table border="1">
<tr>
<td colspan="2"> Birthday List</td>
</tr>

rowspan Attribute
<table border="1">
<tr>
<td rowspan="2">This spans two rows</td>
<td>Row 1 Column 2</td>
</tr>
<tr>
<td>Row 2 Column 2</td>
</tr>
</table>

Accessibility: headers & id Attributes
|------------------------|------------------------------------------------------------------------------------------|
| HTML Attribute | CSS Property |
| align | Align a table: table { width: 75%; margin: auto; } Align within a table cell: text-align |
| bgcolor | background-color |
| cellpadding | padding |
| cellspacing | border-spacing or border-collapse |
| height | height |
| valign | vertical-align |
| width | width |
| border | border, border-style, or border-spacing |
| --- | background-image |
| --- | caption-side |
Tables - add'l context tags
html
<style>
table {
border: 15px solid navy;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding:10px;
}
thead {
font-family:sans-serif, arial;
text-transform:uppercase;
border:5px solid gray
}
</style>
<table>
<thead>
<tr>
<th>Whale</th>
<th>Length</th>
<th>Weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>Blue Whale</td>
<td>100 feet</td>
<td>150 tons</td>
</tr>
...
</tbody>
</table>
Tables - colgroup
html
<style>
.whaleinfo {background-color:LightSkyBlue; width: 300px}
.whale {width:100px}
...
</style>
<table>
<colgroup>
<col class="whale"></col>
<col class="whaleinfo"></col>
<col class="whaleinfo"></col>
<colgroup>
...
CH9 FormBasics
HTML Using Forms
Basic Form Structure
html
<form action="/submit" method="post">
<!-- Form elements go here -->
<button type="submit">Submit</button>
</form>
Key Attributes:
- action: URL where form data is sent
- method: HTTP method (GET or POST)
- enctype: Encoding type for file uploads (multipart/form-data)
Input Elements<input type="text" name="username" placeholder="Enter username">
Common input types:
text, password, email, tel, url, number, range, date, time, datetime-local, color, file, search, checkbox, radio, submit, reset, button
<form> tag
- Contains the form elements on a web page
- Container tag
<input> tag
- Configures a variety of form elements including text boxes, radio buttons, check boxes, and buttons
- Stand alone tag
**<textarea>**tag
- Configures a scrolling text box
- Container tag
<select> tag
- Configures a select box (drop down list)
- Container tag
**<option>**tag
- Configures an option in the select box
- Container tag
Sample Form HTML
html
<form>
E-mail: <input type="text" name="email" id="email" >
<br><br>
<input type="submit" value="Sign Me Up!"> <input type="reset">
</form>
The Form Element <form>
Container Tag
The form element attributes:
action
Specifies the server-side program or script that will process your form data
<form action="/submit-data">
表示:表单提交后,数据会发送给
/submit-data
这个地址(通常是服务器上的脚本,如 PHP、Node、Python、后端 API)
method
- get -- default value, form data passed in URL
- post -- more secure, form data passed in HTTP Entity Body
method 类型 | 解释 | 特点 |
---|---|---|
get (默认) |
数据通过 URL 发送(像这样:?name=chloe&age=18 ) |
适合传少量、不敏感数据 |
post |
数据通过 HTTP 请求体发送(别人看不到) | 适合传大量或敏感数据(密码、评论等) |
name
Identifies the form
id
Identifies the form
属性 | 用途 | 是否唯一 | 主要用于 |
---|---|---|---|
id |
唯一标识一个元素 | ✅ 是唯一的 | JavaScript、CSS、跳转锚点等 |
name |
给元素命名 | ❌ 可重复 | 表单提交、旧版 JS |
id
示例(用于 JS 或 CSS 定位)
name
示例(用于表单提交时传递参数)
<input name="username"> 提交表单时会自动传:username=chloe
The Input Element Text Box <input>
Accepts text information
Common Attributes:
type="text" 、name、id、size、maxlength、value、 required (HTML5)、 placeholder (HTML5)
The Input Element Password Box <input>
Accepts text information that needs to be hidden as it is entered
Common Attributes:
type="password"、name、id、size、maxlength、value、 required (HTML5)、 placeholder (HTML5)
The Input Element Check box <input>
Allows the user to select one or more of a group of predetermined items
Common Attributes:
type="checkbox"、name 、id 、checked 、value
The Input Element Radio Button <input>
Allows the user to select exactly one from a group of predetermined items
Each radio button in a group is given the same name and a unique value
Comon Attributes:
type="radio" 、name 、id 、checked 、value
The Select Element <select>
Configures a select list (along with <option> tags)
Also known as: Select Box, Drop-Down List, Drop-Down Box, and Option Box.
Allows the user to select one or more items from a list of predetermined choices.
Common Attributes:
name、 id 、size 、multiple
The Option Element <option>
Configures the options in a Select List
Attributes: value、selected
The Input Element Submit Button <input>
Submits the form information
When clicked:
- Triggers the action method on the <form> tag
- Sends the form data (the name=value pair for each form element) to the web server.
Attributes:
type="submit" 、name 、id 、value
The Input Element Reset Button <input>
Resets the form fields to their initial values
Attributes:
type="reset" 、name 、id 、value
The Input Element Hidden Field <input>
This form control is not displayed on the Web page.
Hidden form fields :Can be accessed by bothclient-side and server-side scripting
Common Attributes:
type="hidden" 、name 、id 、value
The Label Element <label>
Associates a text label with a form control
Two Different Formats:
<label>Email: <input type="text" name="CustEmail" id ="CustEmail"></label>
Or
<label for="email">Email: </label>
<input type="text" name="CustEmail"id= "email" />
The Fieldset & Legend Elements
The Fieldset Element <fieldset>
- Container tag
- Creates a visual
- group of form controlson a web page
The Legend Element <legend>
- Container tag
- Creates a text labelwithin the fieldset
html
<fieldset><legend>Customer Information</legend>
<label>Name:<input type="text" name="CName" id="CName" size="30"></label>
<br><br>
<label>Email:<input type="text" name="CEmail" id="CEmail"></label>
</fieldset>
Using CSS to Style a Form
css
form { background-color:#eaeaea; font-family: Arial, sans-serif;
width: 350px; padding: 10px;}
label { float: left; clear: left; display: block; width: 100px;
text-align: right; padding-right: 10px; margin-top: 10px; }
input, textarea { margin-top: 10px; display: block;}
input[type= "submit"]{ margin-left: 110px; }

Server-Side Scripting
- .php (PHP)
- .cfm (Adobe ColdFusion)
- .jsp (Sun JavaServer Pages)
- .aspx (ASP.Net).
HTML5: Email Text Box <input>
Accepts text information in e-mail address format
Common Attributes: type="email" name id size maxlength value placeholder required
HTML5: URL Text Box <input>
Accepts text information in URL format
Common Attributes: type="url" name id size maxlength value placeholder required
HTML5: Telephone Number Text Box <input>
Accepts text information in telephone numberformat
Common Attributes: type="tel" name id size maxlength value placeholder required
HTML5: Search Text Box <input>
Accepts search terms
Common Attributes: type="search" name id size maxlength value placeholder required
HTML5: Datalist Control
html
<label for="color">Favorite Color:</label>
<input type="text" name="color" id="color" list="colors" >
<datalist id="colors">
<option value="red">
<option value="green">
<option value="blue">
<option value="yellow">
<option value="pink">
<option value="black">
</datalist>
HTML5: Slider Control <input> (range)
html
<label for="myChoice">
Choose a number between 1 and 100:</label><br>
Low <input type="range" name="myChoice" id="myChoice"> High

HTML5: Spinner Control <input> (number)
html
<label for="myChoice">Choose a number between 1 and 10:</label>
<input type="number" name="myChoice" id="myChoice"
min="1" max="10">

HTML5: Calendar Control <input> (date)
html
<label for="myDate">Choose a Date</label>
<input type="date" name="myDate" id="myDate">
HTML5 Color-well Control(color)
html
<label for="myColor">Choose a color:</label>
<input type="color" name="myColor" id="myColor">
CH10 Advanced Style Transition and Animation
CSS3 Transforms(变形)
transform: translate(x, y); /* 位移 */
transform: rotate(45deg); /* 旋转 */
transform: scale(1.5); /* 缩放 */
transform: skew(20deg, 10deg);/* 倾斜 */
transform: matrix(...); /* 综合变换(不常用) */
例子:
效果:鼠标悬停时,这个方块会旋转 + 放大 + 平移,非常有趣
css
<div class="box">🌟</div>
<style>
.box {
width: 100px;
height: 100px;
background-color: skyblue;
text-align: center;
line-height: 100px;
transition: transform 0.5s;
}
.box:hover {
transform: rotate(15deg) scale(1.2) translateX(20px);
}
</style>
CSS3 Transitions(过渡)
可以让属性变化变得平滑,比如颜色渐变、大小变大等,而不是一下子跳变。
transition : property duration timing-function delay;
部分 | 意义 |
---|---|
property |
要过渡的属性(如 transform 、background-color ) |
duration |
持续时间,如 0.5s |
timing-function |
速度曲线,如 ease 、linear 、ease-in-out |
delay |
延迟时间(可选) |
例子:
效果:按钮颜色渐变变深,同时轻轻放大,动感十足
css
<button class="btn">Click Me</button>
<style>
.btn {
padding: 10px 20px;
background-color: salmon;
color: white;
border: none;
font-size: 16px;
transition: background-color 0.3s ease, transform 0.3s ease;
}
.btn:hover {
background-color: tomato;
transform: scale(1.1);
}
</style>
CSS3 Animation
Animation properties:
属性 | 作用 |
---|---|
@keyframes |
定义动画的关键帧 |
animation-name |
使用哪个关键帧 |
animation-duration |
动画持续时间(比如 2s ) |
animation-timing-function |
动画节奏(如 ease , linear ) |
animation-delay |
延迟多久开始 |
animation-iteration-count |
循环次数(如 infinite 无限循环) |
animation-direction |
是否反方向(如 alternate ) |
animation-fill-mode |
动画结束后状态(如 forwards 保持结束样式) |
Basic Animation Structure
/* 第一步:定义动画关键帧 */
@keyframes 动画名 {
0% { ...起始状态... }
100% { ...结束状态... }
}
/* 第二步:应用动画样式 */
.元素类名 {
animation-name: 动画名;
animation-duration: 时间;
...其他设置...
}
例子:
-
slideRight
是动画名 -
每 2 秒来回左右移动
-
infinite
:无限循环 -
alternate
:来回走 -
ease-in-out
:速度先慢后快再慢
html
<div class="box">🎈</div>
<style>
/* 定义动画关键帧:从左移到右 */
@keyframes slideRight {
0% { transform: translateX(0); }
100% { transform: translateX(300px); }
}
.box {
width: 100px;
height: 100px;
background-color: lightseagreen;
color: white;
font-size: 40px;
text-align: center;
line-height: 100px;
border-radius: 10px;
/* 应用动画 */
animation-name: slideRight;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-in-out;
}
</style>
CH11 JavaScript
Introduction
JavaScript is a scripting language(脚本) most often used for client-side(用户端) web development.
JavaScript is an implementation of the ECMAScript standard.
Uropean Computer Manufacturers Association Script: the syntax/characteristics of the language and a basic set of commonly used objects
语言的语法和特性以及一组基本的常用对象
JScript is the Microsoft version of JavaScript.
Three places to add JavaScript
internal script - put in <head> section
<head> <script> JavaScript statement(s) </script> </head>
external JavaScript file - place an external script reference in <head> or <body>
<script src="mycode.js"> </script>
inline script - put in <body> section
<body> <script> JavaScript statement(s) </script> </body>
Web specific functions
alert("Hello World!"); //显示一个弹出提示框;
document.write("Hello"); //向页面写入文本;
document.getElementById("bluetext").innerHTML = "new text"; //把 id 为 "bluetext" 的元素内容改为 "new text";
document.getElementById("completed").src = "yes.png"; //id 为 "completed" 的图像的图片地址改为 "yes.png";
DOM
Document Object Model
Before changing DOM, page must be completely loaded
javascript
function init()
{
let nm = document.getElementById("name");
nm.innerHTML = "Jessie";
}
window.onload = init;
//整个网页加载完成后,执行 init() 函数。
JavaScript Output
JavaScript can "display" data in different ways:
- Writing into an HTML element , using innerHTML.
- Writing into the HTMLoutput using document.write().
- Writing into an alert box , using window.alert().
- Writing intothe browser console , using console.log().
1.Using innerHTML
javascript
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
这段代码会找到网页中 id 是 "demo" 的 <p> 标签,然后把它里面的内容改成 5 + 6 的计算结果,也就是 11,显示在页面上。(使用"5+6"才会显示"5+6")
2.Using document.write()
javascript
<script>
document.write(5 + 6);
</script>
但如果在页面完全加载后使用 document.write(),会清除页面上所有已有的 HTML 内容
这段代码会直接在页面上写入 11。 注意:如果你在页面加载完成后再调用 document.write(),页面之前的所有内容都会被清空,只剩下写入的新内容。
3.Using window.alert()
javascript
<script>
window.alert(5 + 6);
</script>
页面加载时,会弹出一个对话框,显示计算结果 11,用户点击确定才能关闭这个弹窗。
4.Using console.log() :
javascript
<script>
console.log(5 + 6);
</script>
这个不会显示在网页上,而是把 11 显示在浏览器的开发者工具控制台(Console 面板)里,方便程序员查看调试信息。
Javascript statement
Values(值)、Operators(运算符)、Expressions(表达式)、Keywords(关键字)、Comments(注释)
let temp=98.6; // fahrenheit
let firstName = "Adam";
let lastName = "Zigler";
temp = (temp - 32) * 5 / 9;
let fullname = firstName + " " + lastName;
let randomNum = Math.random();
let count=5;
count=count+1
Embedding JavaScript
html
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
</html>
Usethe src attribute to include JavaScript codes from an external file.
The included code is inserted in place.
Hiding JavaScript from Incompatible Browsers
html
<noscript>
<p>This website requires JavaScript to function properly. Please enable it or use a modern browser.</p>
</noscript>
如果用户的浏览器不支持 JavaScript 或已禁用,浏览器就会显示 <noscript> 中的内容。
它既可以写在 <head> 里(用于元信息提示),也可以写在 <body> 里(显示给用户看)。
alert(), confirm(), and prompt()
alert("Text to be displayed");
这个对话框只有一个"确定"按钮。它会阻止用户继续操作网页,直到点击"确定"。
var answer = confirm("Are you sure?");
confirm() returns true if the user click "OK". Otherwise it returns false
prompt("What is your student id number?");
prompt("What is your name?", "No name");
prompt() 是 JavaScript 中用来弹出一个输入框,让用户输入内容的方法。输入框中默认显示 "No name"。如果不写第二个参数(默认值),那么输入框是 空白的。用户点击 "确定" → 返回用户输入的内容(字符串)。 用户点击 "取消" → 返回 null(表示没输入)。
Identifier
- Contains only 'A' -- 'Z', 'a' -- 'z', '0' -- '9', '_', '$'
- First character cannot be a digit
- Case-sensitive
- Cannot be reserved words or keywords
JavaScript Statements
html
<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">
document.write('<h1>This is my first
JavaScript Page</h1>');
</script>
</body>
</html>
HTML written inside JavaScript
html
<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseover="window.alert('Hello');">
My Page</a>
</p>
</body>
</html>
onMouseover 是HTML元素上的一个事件属性,意思是鼠标移到这个元素上时触发。 这里的意思是,当用鼠标"悬停"在第二个链接上时,会执行里面的JavaScript代码。
html
<script language="JavaScript">
window.prompt('Enter your name:','');
</script>
这里弹出一个对话框,提示内容是 "Enter your name:",并且输入框初始是空的(第二个参数''表示默认值)。 用户可以在弹窗里输入自己的名字,然后点击"确定"或"取消"。 这个弹窗出现时页面会暂停操作,直到用户做出输入。
html
<form>
<input type="button" Value="Press" onClick="window.alert('Hello');">
</form>
当用户点击这个按钮时,会触发按钮的onClick事件,执行JavaScript代码
JavaScript 就是通过 DOM 来访问网页里的内容和结构。
Forms and JavaScript
html
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
document.formname.elementname.value
- document.addressform.yourname.value
- document.addressform.phone.value
- document.addressform.email.value
html
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go" onClick="window.alert('Hello ' + document.alertform.yourname.value);">
</form>
Variable and Variable Declaration
html
<head><script type="text/javascript">
// We are in the default scope -- the "window" object.
x = 3; // same as "window.x = 3"
let y = 4; // same as "y = 4" or "window.y = 4"
{ // Introduce a block to creat a local scope
x = 0; // Same as "window.x = 0"
y = 1; // This is a local letiable y
}
alert("x=" + x + ", y=" + y); // Print x=0, y=4
</script></head>
- 没有用 let 或 var 声明,全局变量。
- JavaScript 是 动态类型语言。
- 本地(局部)变量可以用 var 声明(不过现在推荐用 let 和 const)。
- 没有声明就直接用一个变量名,JavaScript 会自动创建一个全局变量。
Hoisting in JavaScript
有"声明"被提升,赋值不会被提升。
用 let 或 const 声明的变量也会被提升,但在被赋值前 ,处于"暂时性死区Temporal Dead Zone (TDZ)",访问会出错。
Variable Hoisting
JavaScript 在执行代码前,会先把变量声明"悄悄"移到最上面。
javascript
console.log(x); // undefined (hoisted)
var x = 5;
console.log(x); // 5
因为 x 被提升了,但还没赋值。
javascript
console.log(y); // ❌ ReferenceError (TDZ)
let y = 10;
console.log(y); // 10
var 提升 + 默认 undefined ,不报错 ;let/const 提升但没值,在赋值前 访问会直接报错(TDZ)。
Function Hoisting
Function Declarations (Fully Hoisted) 函数声明(会被提升)
Can be called before declaration.
javascript
sayHello(); // "Hello!" (works)
function sayHello() {
console.log("Hello!");
}
Function Expressions (Not Hoisted) 函数表达式(不会被提升)
Behaves like variables (var → undefined, let/const → TDZ).
javascript
greet(); // ❌ TypeError (var: undefined) / ReferenceError (let/const)
var greet = function() { console.log("Hi!"); };
greet 被提升为 undefined,所以调用 greet() 相当于调用 undefined(),就报错了。
Class Hoisting
Classes (class) are not hoisted (unlike functions).
Must be declared before use.
javascript
const obj = new Person(); // ❌ ReferenceError
class Person {}
先看一遍整个代码,把变量和函数的声明"收集起来",所以就出现了"提升"。
JavaScript Variables: Types and Scope
A. var(Old Way, Function-Scoped)
- Scope: Function-level or global.
- Hoisting: Yes (initialized as undefined).
- Re-declaration: Allowed (can cause bugs).
- Reassignment: Allowed.
var 的作用范围是"整个函数或全局"。
javascript
var x = 10;
if (true) {
var x = 20; // Same variable (global)
}
console.log(x); // 20 (changed globally)
在 if 里面定义的 x,其实跟外面的 x 是同一个变量!
B. let(Modern, Block-Scoped)
- Scope: Block-level ({}).
- Hoisting: Yes, but in Temporal Dead Zone (TDZ) (throws error if accessed before declaration).
- Re-declaration: Not allowed in the same scope.
- Reassignment: Allowed.
javascript
let y = 10;
if (true) {
let y = 20; // Different variable (block-scoped)
console.log(y); // 20
}
console.log(y); // 10 (outer scope unchanged)
C. const(Modern, Block-Scoped, Immutable)
- Scope: Block-level ({}).
- Hoisting: Yes (TDZ applies).
- Re-declaration: Not allowed.
- Reassignment: Not allowed (but object/array properties can be modified).但是对象的"内容"可以改!
javascript
const z = 30;
// z = 40; ❌ Error (reassignment not allowed)
const person = { name: "Alice" };
person.name = "Bob"; // ✅ Allowed (object property change)
D. UndeclaredVariables (Avoid!)
- Scope: Global (accidental pollution).
- Hoisting: No.
- Strict Mode: Throws ReferenceError.
javascript
a = 5; // ❌ Avoid! (global variable)
console.log(a); // 5 (works, but bad practice)
Variable Scope in JavaScript
A. Global Scope
Variables declared outside any function or block.
Accessible everywhere (risky due to naming collisions
在任何函数、花括号 {} 外面定义变量,那就是"全局变量"。
javascript
var globalVar = "I'm global!";
function checkScope() {
console.log(globalVar); // "I'm global!"
}
checkScope();
B. Function Scope (var)
Variables declared inside a function are local to it.
在函数里用 var 声明的变量,只能在函数里面用
javascript
function demo() {
var localVar = "I'm local!";
console.log(localVar); // "I'm local!"
}
demo();
// console.log(localVar); ❌ Error (not accessible outside)
C. Block Scope (let, const)
Variables inside {} (if, for, while) are block-scoped.
在 if、for、while、{} 这种"代码小房子"里,用 let 或 const 声明的变量,只在这小房子里能用
javascript
if (true) {
let blockVar = "I'm block-scoped!";
console.log(blockVar); // "I'm block-scoped!"
}
// console.log(blockVar); ❌ Error (not accessible outside)
