网络技术与应用

HTML 5

HTML5概述

因特网上的信息是以网页的形式展示给用户的,因此网页是网络信息传递的载体。网页文件是用HTML(Hyper Text Markup Language,超文本标记语言)书写的。

HTML5不是一种编程语言,而是一种描述性的标记语言,用于描述超文本中的内容和结构。

HTML5结构

HTML5文件的基本结构

HTML标记符一般有两种:

  • 一般标记符(容器标记符)

    这些标记符的起始部分与结束部分必须成对出现

  • 空标记符

    只是单一的一个标记符而已,如<hr>标记符

HTML文件的编写方法

  • 记事本

    保存文件时,选择【保存类型】为【所有文件】,将文件的扩展名设置为.htm或.html。建议将文档的编码设置为utf-8,默认是ANSI。

  • IntelliJ IDEA、Dreamweaver、Editplus等工具

编写第一个HTML5页面

测试浏览器是否支持HTML5(画布标记)

chap1-1.html

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type"content="text/html" charset="utf-8">
<title>测试</title>
<styletype="text/CSS">
#myCanvas{
  background:red;
  width:200px;
  height:100px;
}
</style>
</head>
<body>
<canvas id="myCanvas">该浏览器不支持HTML5的画布标记!</canvas>
</body>
</html>

常用HTML实体

字符 实体名称 实体编号 字符 实体名称 实体编号
< &lt; &#60; > &gt; &#62;
& &amp; &#30; &euro; &#8364;
£ &pound; &#163; § &sect; &#167;
© &copy; &#169; ® &reg; &#174;
&trade; &#8482; 空格 &nbsp; &#160;
" &quot; &#34; ° &deg; &#176;
± &plusmn; &#177; ² &sup2; &#178;

HTML5全局属性

全局属性可以用来配置所有元素共有的行为,可以用在任何一个元素身上。

  • accesskey属性

    设置页面上元素的快捷键。Windows系统上同时按下Altaccesskey属性值可以触发accesskey机制。

  • lang属性

    用于说明元素内容使用的语言。中文为zh,英文为en

    chap1-2.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>chap1-2</title>
      </head>
      <body>
        <form>
          Name:<input type="text" name=“user" accesskey="n"><br/>
          password:<input type="password" name=“upw" accesskey="p">
        </form>
      </body>
    </html>
    
  • class属性

    用来将元素归类,通常是为了能够找出文档中的某一类元素或为某一类元素应用CSS样式。

  • contenteditable属性

    让用户能够修改页面上的内容。

    chap1-3.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>chap1-3</title>
        <style type="text/css">
          .class2{
            background: gray;
            color: white;
            padding: 5px;
            margin: 2px;
          }
          .class1{
            font-size: x-large;
          }
        </style>
      </head>
      <body>
        <p class="class2" contenteditable="true">hello world</p>
        <p class="class1">hello world</p>
      </body>
    </html>
    
  • dir属性

    用来规定元素中文字的方向,其有效值有:

    • ltr:从左到右;

    • rtl:从右到左。

  • id属性

    用来给元素分配一个唯一的标识符,通常用来将样式应用到元素上或在JavaScript程序中用来选择元素。

    chap1-4.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>chap1-4</title>
        <style type="text/css">
          #w1{
            background: gray;
            color: white;
            padding: 5px;
            border: thin solid black;
          }
        </style>
      </head>
      <body>
        <p id="w1" dir="ltr">hello world</p>
        <p id="w2" dir="rtl">hello world</p>
      </body>
    </html>
    
  • spellcheck属性

    用来表明浏览器是否应该对元素的内容进行拼写检查。这个属性只有用在用户可以编辑的元素上时才有意义。

  • style属性

    用来直接在元素身上定义CSS样式(这是在style元素或外部样式表中定义样式之外的一种选择)

    chap1-5.html

    <!DOCTYPE html>
    <html lang="zh">
      <head>
        <meta charset="UTF-8">
        <title>chap1-5</title>
      </head>
      <body>
      <p style="background: gray;color: white;padding: 10px">留言:</p>
        <textarea spellcheck="true"></textarea>
      </body>
    </html>
    
  • tabindex属性

    用来设置元素的顺序,实现通过按Tab键在各元素之间切换。设置为-1的元素不会在用户按下Tab键后被选中。

  • title属性

    用来设置元素的额外信息。通常被用来显示工具提示。

    chap1-6.html

    <!DOCTYPE html>
    <html lang="zh">
      <head>
        <meta charset="UTF-8">
        <title>chap1-6</title>
      </head>
      <body>
      <p>用户:<input type="text" tabindex="1"></p>
        <p>密码:<input type="password" tabindex="-1"></p>
        <p>留言:<textarea title="留言" tabindex="2"></textarea></p>
      </body>
    </html>
    

HTML标记

HTML文档最基本的结构主要包括

  • 文档类型说明:<!DOCTYPE html>
  • HTML文档开始标记:<html>…</html>
  • 头标记:<head>…</head>
  • 主体标记:<body>…</body>
  • 页面注释标记:``

每一个HTML文档都必须以doctype元素开头,浏览器据此得知自己将要处理的是HTML内容。

HTML元素表示文档中HTML部分的开始。

head元素包含着文档的元数据,从而向浏览器提供有关文档内容和标记的信息,此外还可以包含脚本和对外部资源(比如CSS样式表)的引用。

body元素包含着文档的内容。

head标记

元素 说明
title 设置文档标题
style 定义CSS样式
meta 提供关于文档的信息
base 设置相对URL的基础
link 定于与外部资源(通常是样式或网站图标)的关系
script 定义脚本程序,可以是文档内嵌的,也可以是外部文件中的
noscript 包含浏览器禁用脚本或不支持脚本时显示的内容

base元素

用来设置一个基准URL,让HTML文档中的相对链接在此基础上进行解析。

  • href属性

    指定基准URL

  • Target属性

    指定浏览器如何打开URL。

    说明 说明
    _blank 新窗口中 _top 顶层窗口中
    _parent 父窗框组中 <frame> 指定窗框中
    _self 当前窗口中

chap1-7.html

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8">
    <title>chap1-7</title>
    <style type="text/css">
      .class1{
        background: gray;
        color: white;
      }
    </style>
    <base href="linktest/" target="_blank">
  </head>
  <body>
    <a href="basetest.html" class="class1">base测试</a>
  </body>
</html>

meta元素

  • 通过namecontent属性指定名/值元数据对

    元数据名称 说明
    Application name 当前页所属Web应用系统名称
    Author 当前页的作者
    Description 当前页的说明
    Generator 用来生成HTML的软件名称
    Keywords 一批以逗号分开的字符串,用来描述页面的内容
  • 通过charset声明字符编码

  • 通过http-equivcontent改写HTTP标头字段的值,http-equiv有3个值可用:

    属性值 说明
    Refresh 以秒为单位指定一个时间间隔,在此时间过去之后将从服务器重载当前页面,也可以另行指定一个URL让浏览器载入。<meta http-equiv="refresh" content="5;chap1-1.html">
    Default-style 指定页面优先使用的样式表。对应的content属性值应与同一文档中某个style元素或link元素的title属性值相同。
    Content-type 这是另一种声明HTML页面所用字符编码的方法<meta http-equiv="content-type" content="text/html charset=UTF-8">

chap1-8.html

<!DOCTYPE html>
<html lang="zh">
  <head>
    <title>chap1-8</title>
    <base href="linktest/" target="_blank">
    <meta http-equiv="content-type" content="text/html charset=utf-8">
    <meta http-equiv="refresh" content="5;basetest.html">
    <meta name="author" content="shulinChen">
  </head>
  <body>
    <p>5秒后页面跳转</p>
  </body>
</html>

style元素

用来定义HTML文档内嵌的CSS样式,其属性有:

  • type属性:用来将所定义的样式类型告诉浏览器。值只有一个:text/css。

  • media属性:用来表明文档在什么情况下应该使用该元素中定义的样式,常用有:

    • screen:用于计算机显示器屏幕;
    • print:用于打印预览和打印页面;
    • projection:用于投影机

chap1-9.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>chap1-9</title>
    <style type="text/css" media="screen">
      a{
        background: gray;
        color: white;
        padding: 10px;
      }
    </style>
    <style type="text/css" media="print">
      a{
        color: red;
        font-weight: bold;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <p><a href="chap1-1.html">chap1-1.html</a></p>
    <p><a href="chap1-2.html">chap1-2.html</a></p>
  </body>
</html>
  • link元素

    用来在HTML文档和外部资源(CSS样式表)之间建立联系。其属性有:

    • href:指定link元素指向的资源的URL;
    • rel:说明文档与所关联资源的关系类型,如stylesheet(载入外部样式表)
    • type:指定所关联资源的MIME类型,如text/css
      chap1-10.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-10</title>
    <link rel="stylesheet" type="text/css" href="css1/chap1-10.css">
  </head>
  <body>
  <a href="chap1-1.html">chap1-1.html</a>
  </body>
</html>

chap1-10.css

a{
  background: grey;
  color: white;
  padding: 10px;
}

script元素

用来在页面中加入脚本,方法有在文档中定义脚本和引用外部文件中的脚本两种。其属性有:

  • type:表示所引用或定义的脚本的类型,缺省为JavaScript脚本。
  • src:指定外部脚本文件的URL。
  • charset:说明外部脚本所用字符编码,该属性只能与src属性一同使用。

chap1-11.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-11</title>
    <script src="js/chap1-11.js"></script>
    <script>
      document.write("<br>");
      document.write("This is from the script");
    </script>
  </head>
  <body>
    <p><a href="chap1-1.html">chap1-1.html</a> </p>
  </body>
</html>

chap1-11.js

document.write("This is from the external script");

noscript元素

用来向禁用了JavaScript或浏览器不支持JavaScript的用户显示一些内容。

chap1-12.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-12</title>
    <script src="js/chap1-11.js"></script>
    <noscript>
      <h1>Javascript is required!</h1>
      <p>You cannot use this pape without JavaScript</p>
    </noscript>
  </head>
  <body>
    <p><a href="chap1-1.html">chap1-1.html</a></p>
  </body>
</html>

body标记

通过添加文本元素,构造网页内容。

原则:

  • 如果存在符合需求的专用元素就用这种元素;
  • 避开那些补了点语义脂粉的呈现性元素(如b元素),把呈现工作交给CSS打理;
  • 不管选择使用什么元素,都要在HTML文档中贯彻始终。

生成超链接

通过a元素生成超链接。其属性有:

  • href属性:指定a元素所指资源的URL。
    • 外部超链接
      • 绝对地址:资源的完整路径;
      • 相对地址:资源相对于当前文档的路径。
    • 内部超链接:通过设置目标元素的id属性

chap1-13.html

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8">
    <title>chap1-13</title>
  </head>
  <body>
    <h1><a href="chap1-1.html">相对路径</a></h1>
    <h1><a href="http://localhost/myweb/chap1/chap1-2.html">绝对路径</a></h1>
    <h1><a href="#position1">内部超链接</a></h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1>hello world</h1>
    <h1 id="position1">内部超链接</h1>
  </body>
</html>
  • target属性:指定用以打开所链接资源的浏览环境,其值:
    • _blank:在新窗口中打开;
    • _parent:在父窗框组(frameset)中打开;
    • _self:在当前窗口打开(默认);
    • _top:在顶层窗口打开;
    • <frame>:在指定窗框中打开。

基本的文字元素

b元素:内容加粗{font-weight:bolder;}

em元素:内容强调{font-style:italic;}

i元素:外文词语或科技术语{font-style:italic;}

s元素:删除线{text-decoration:line-through;}

strong元素:重要文字{font-weight:bolder;}

u元素:下划线{text-decoration:underline;}

small元素:小号字体内容{font-size:smaller;}

sub元素:下标{vertical-align:sub;font-size:smaller;}

sup元素:上标{vertical-align:super;font-size:smaller;}

chap1-14.html

<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8">
   <title>chap1-14</title>
 </head>
 <body>
   <p><b>hello world</b></p>
   <p><em>hello world</em></p>
   <p><i>hello world</i></p>
   <p><s>hello world</s></p>
   <p><strong>hello world</strong></p>
   <p><u>hello world</u></p>
   <p><small>hello world</small></p>
   <p>x<sub>1</sub><sup>2</sup></p>
 </body>
</html>

换行

br元素:将后续内容转移到新行上。

wbr元素:用来表示长度超过当前浏览器窗口的内容适合在此换行,究竟换不换行由浏览器决定。因此,wbr元素只不过是对恰当的换行位置的建议而已。

chap1-15.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-15</title>
  </head>
  <body>
    Hello world!<br>
    This is a very long word: super<wbr>califragilistic<wbr>expialidocious.
    We can help the browser display long words with the <code>wbr</code> element.
  </body>
</html>

表示输入和输出

code元素:表示计算机代码片段{font-family:monospace;}

var元素:表示变量{font-style:italic;}

samp元素:表示程序或计算机系统的输出{font-family:monospace;}

kbd元素:表示用户输入{font-family:monospace;}

chap1-16.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-16</title>
  </head>
  <body>
    <p><code>var fruits=["apples","oranges","mangoes","cherries"];<br>
      document.writeln("I like" + fruits.length + " fruits");</code></p>
    <p>The variable in this example is <var>fruits</var></p>
    <p>The output from the code is: <samp>I like 4 fruits</samp></p>
    <p>When prompted for my favorite fruit, I typed: <kbd>cherries</kbd></p>
  </body>
</html>

科学和学术标记

abbr元素:表示缩写{text-decoration: dotted underline;}

dfn元素:表示定义中的术语{font-style:italic;}

cite元素:表示所引用作品的标题{font-style:italic;}

q元素:表示引自他处的内容,其cite属性可以用来指定来源文章的URL。

q{display:inline;}
q:before{content:open-quote;}
q:after{content:close-quote;}

chap1-17.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-17</title>
  </head>
  <body>
    <p>The <abbr title="Florida Department of Citrus">FDOC</abbr> regulates the Florida citrus industry.</p>
    <p>The <dfn title="Florida Department of Citrus">FDOC</dfn> regulates the Florida citrus industry.</p>
    <p>My favorite book on fruit is <cite>Fruit: Edible, Inedible, Incredible</cite> by Stuppy & Kesseler.</p>
    <q cite="https://en.wikipedia.org/wiki/Primary_production#GPP_and_NPP"><abbr title="Gross primary production"><cite>GPP</cite></abbr> is the amount of chemical energy as biomass that primary producers create in a given length of time. </q>
  </body>
</html>

其他文本元素

span元素:本身没有任何含义,它可以用来把一些全局属性应用到一段内容上。

mark元素:表示因为与某段上下文相关而被突出显示的一段文字。mark{background-color:yellow;color:black;}

ins元素和del元素可以分别用来表示文档中添加和删除的文字。ins{text-decoration:underline;}del{text-decoration:line-through;}

组织内容

元素 说明
p 表示段落
div 将全局属性应用到一片内容上
pre 保留HTML文档中的布局
blockquote 表示引自他处的内容
hr 表示段落级别的主题转变
olli 生成有序列表
ulli 生成无序列表
dldtdd 生成术语及其定义的列表
figurefigcaption 表示插图(及可有可无的标题)

div元素作用相当于span元素。它没有具体含义。不建议使用

pre元素让源文档中的格式得以保留。

blockquote元素表示引自他处的一片内容,blockquote{display:block;margin-before:1em;margin-after:1em;margin-start:40px;margin-end:40px;}

chap1-19.html

<head>
  <title>chap1-19</title>
  <style type="text/css">
    .favorites{
      background: gray;
      color: white;
      border: thin solid black;
      padding: 10px;
    }
  </style>
</head>
<body>
  <div class="favorites">
    <p>hello world</p>
  </div>
  <pre><code>
  var fruits=["apples","oranges","mangoes","cherries"];
  document.writeln("I like" + fruits[0]);
  </code></pre>
  <p>Gross primary production …</p>
  <blockquote cite="https://en.wikipedia.org/wiki/Primary_production#GPP_and_NPP"><abbr title="Gross primary production"><cite>GPP</cite></abbr> is the amount of chemical energy as …</blockquote>
</body>

hr元素,在HTML5中代表段落级别的主题分隔。

ol元素表示有序列表,列表项目用li元素表示,其属性有:

  • start属性:设定列表首项编号值,缺省为1

  • reversed属性:编号采用降序。

  • type属性:设定编号的类型。

    type 说明 示例
    1 十进制数(默认) 1.、2.、3.
    a 小写拉丁字母 a.、b.、c.
    A 大写拉丁字母 A.、B.、C.
    i 小写罗马数字 i.、ii.、iii.
    I 大写罗马数字 I.、II.、III.

li元素表示列表中的项目,其属性有:

  • value属性:仅用于父元素是ol元素时,可以用来生成不连续的有序列表。

ul元素生成无序列表。

chap1-20.html

<head>
  <meta charset="UTF-8">
  <title>chap1-20</title>
</head>
<body>
  I like apples and oranges.
  <hr>
  I also like:
  <ol>
    <li>bananas</li>
    <li value="4">mangoes</li>
    <li>cherries</li>
    <li value="7">plums</li>
    <li>peaches</li>
    <li>grapes</li>
  </ol>
  <hr>
  I also like:
  <ul>
    <li>bananas</li>
    <li>mangoes</li>
  </ul>
</body>

dl元素表示说明列表

dt元素表示说明列表中的术语,dt{display:block;}

dd元素表示说明列表中的定义,dd{display:block;margin-start:40px;}

chap1-21.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-21</title>
  </head>
  <body>
    I like:
    <dl>
      <dt>Apple</dt>
      <dd>The apple is the pomaceous fruit of the apple tree</dd>
      <dd><i>Malus domestica</i></dd>
      <dt>Banana</dt>
      <dd>The banana is the parthenocarpic fruit of the banana tree</dd>
      <dd><i>Musa acuminata</i></dd>
    </dl>
  </body>
</html>

figure元素定义插图,习惯样式:figure{display:block;margin-start:40px;margin-end:40px;}

figcaption元素定义插图标题。

chap1-22.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-22</title>
  </head>
  <body>
    I like apples.
    <figure>
      <img src="pic/apple.jpg" width="500" height="380">
      <figcaption>Figure 1. The picture of apple</figcaption>
    </figure>
  </body>
</html>

文档分节

元素 说明
h1~h6 表示标题
section 表示一个重要的主题或概念
headerfooter 表示一节的首部和尾部
nav 表示导航元素集合
article 表示可独立发布的重要主题或概念
aside 表示周边内容的一些沾边话题
address 表示文档或文章的联系信息
detailssummary 生成一个区域,用户可将其展开以了解更多细节

h1~h6元素表示标题。

chap1-23.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-23</title>
  </head>
  <body>
    <script>
      for(var i=1;i<=6;i++){
        document.writeln("<h"+i+">"+"I like apples" + "</h"+i+">");
      }
    </script>
  </body>
</html>

section元素表示的是文档中的一节。至于什么情况下应该使用section元素,并没有明确的规定。不过从经验上讲,section元素用来包含的是那种应该列入文档大纲或目录中的内容。通常包含一个或多个段落及一个标题。

chap1-24.html

<html lang="en">
  <head>
    <title>chap1-24</title>
  </head>
  <body>
    <section>
      <h1>Fruits I Like</h1>
      <h2>How I Learned to love citrus</h2>
      I like apples and oranges.
      <section>
        <h1>Additional fruits</h1>
        I also like bananas, mangoes.
        <section>
          <h1>More information</h1>
          I also like cherries, and peaches.
        </section>
      </section>
    </section>
    <h1>Activities I like</h1>
    <p>I like to swim, cycle and run.</p>
    <h2>Kinds of Triathlon</h2>
    There are different kinds of triathlon - sprint, Olympic and so on.
  </body>
</html>

header元素表示一节的首部,里面可以包含各种适合出现在首部的东西,包括刊头或徽标。

footer元素是header元素的配套元素,表示一节的尾部,通常包含着该节的总结信息,还可以包含作者介绍、版权信息、到相关内容的链接、徽标及免责声明等。

chap1-25.html

<head>
  <title>chap1-25</title>
  <style>
    header, footer {
      border: medium solid black;
      padding-left: 5px;
      margin: 10px 0 10px 0px;
    }
  </style>
</head>
<body>
  <header>
    <h1>Things I like</h1>
    <h2>by Shulin Chen</h2>
  </header>
  <section>
    I like apples and oranges.
  </section>
  <footer id="mainFooter">
    &#169;2017, Shulin Chen. <a href="chap1-1.html"> chap1-1.html</a>
  </footer>
</body>

nav元素表示文档中的一个区域,它包含着到其他页面或同一页面的其他部分的链接。该元素的目的是规划出文档的主要导航区域。

chap1-26.html

<style> nav {text-align:left; padding: 2px;border: dashed thin black;}
  ul > li > a {padding: 2px;color: red;}
</style>
<body>
  <header>
    <nav>
      <h1>contents</h1>
      <ul>
        <li><a href="chap1-1.html">chap1-1</a></li>
        <ul>
          <li><a href="chap1-2.html">chap1-2</a></li>
        </ul>
        <li><a href="chap1-3.html">chap1-3</a></li>
      </ul>
      <ol>
        <li><a href="chap1-3.html">chap1-3</a></li>
      </ol>
    </nav>
  </header>
  <footer id="mainFooter">
    &#169;2017, Shulin Chen.
  </footer>
</body>

article元素代表HTML文档中一段独立成篇的内容。一篇新文章和博文条目都是这方面的典型例子。

chap1-27.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-27</title>
    <style>
      article{border: thin black solid;padding: 10px;margin-bottom: 5px}
      article > footer{background: gray;color: white}
    </style>
  </head>
  <body>
    <article>
      <header>
        <h1>Fruits I Like</h1>
      </header>
      I like apples and oranges.
      <footer>
        &#169;2017, Shulin Chen.
      </footer>
    </article>
  </body>
</html>

aside元素用来表示跟周边内容稍沾一点边的内容,类似于书籍或杂志中的侧栏。其内容与页面其他内容、articlesection有点关系,但并非主体内容的一部分。它可能是一些背景信息、到相关文章的链接等。

chap1-28.html

<head><style>article{border: thin black solid;padding: 10px;margin-bottom: 5px}
  aside{width: 40%;background: white;float: right;border: thick solid black;margin-left: 5px}
  aside > section{padding: 5px}
  aside > h1{background: white;color: blue;text-align: center}</style></head>
<body><article><header>
  <h1 id="fruitslike">Fruits I Like</h1>
  <h2>How I Learn to Love Citrus</h2>
  </header>
  <aside>
    <h1>Why Fruit is Healthy</h1>
    <section>
      Here are three reasons why everyone should eat more fruit:
      <ol>
        <li>Fruit contains lots of vitamins</li>
        <li>Fruit is a source of fibre</li>
        <li>Fruit contains few calories</li>
      </ol>
    </section>
  </aside>
  <p>I like apples and oranges</p>
  <footer>
    &#169;2017, Shulin Chen.
  </footer>
  </article>
</body>

address元素用来表示文档或article元素的联系信息。address{display:block;font-style:italic}

address元素身为article元素的后代元素时,它提供的联系信息被视为该article的。否则,当address元素身为body元素的子元素时,它提供的联系信息被视为整个文档的。

chap1-29.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      article{border: thin black solid;padding: 10px;margin-bottom: 5px}
    </style>
  </head>
  <body>
    <article>
      <header>
        <h1 id="fruitslike">Fruits I Like</h1>
        <h2>How I Learn to Love Citrus</h2>
      </header>
      <address>
        Questions and comments? <a href="mailto:chenshulin0923@163.com">Email me</a>
      </address>
      <footer>
        &#169;2017, Shulin Chen.
      </footer>
    </article>
  </body>
</html>

details元素在文档中生成一个区域,用户可以展开它以了解关于某主题的更多详情。

details元素通常包含一个summary元素,其作用是为该详情区域生成一个说明标签或标题。

chap1-30.html

<head>
  <meta charset="UTF-8">
  <title>chap1-30</title>
  <style>
    article{border: thin black solid;padding: 10px;margin-bottom: 5px}
    details{border: solid thin black;padding: 5px}
    details > summary{font-weight: bold}
  </style>
</head>
<body>
  <section>
    <p>I like to swim, cycle and run. I am in training for my first triathlon, but it is hard work.</p>
    <details>
      <summary>Kinds of Triathlon</summary>
      There are different kinds of triathlon - sprint, Olympic and so on. I am aiming for Olympic, which consists of the following:
      <ol>
        <li>1.5km swim</li>
        <li>40km cycle</li>
        <li>10km run</li>
      </ol>
    </details>
  </section>
</body>

表格

元素 说明
tabletrtd 生成基本的表格
th 为表格添加表头单元格
theadtbody 区分行表头和列表头
tfoot 为表格添加表脚
caption 为表格添加标题
colgroupcol 对表格按列处理而不是按行处理

每一个表格都必须要有:tabletrtd这三个元素。

table元素的属性有border,习惯样式table{display:table; border-collapse:separate;border-spacing:2px; border-color:gray}

tr元素习惯样式tr{display:table-row; vertical-align:inherit;border-color:inherit}

td元素属性有:colspanrowspanheaders,习惯样式td{display:table-cell;vertical-align:inherit}

  • colspan属性:在列方向上合并单元格;
  • rowspan属性:在行方向上合并单元格;
  • headers属性:规定表头与单元格相关联,该属性不会在普通浏览器中产生任何视觉变化。

th元素表示表头的单元格,用来区分数据和对数据的说明。习惯样式:th{display:table-cell;vertical-align:inherit;font-weight:bold; text-align:center}

chap1-31.html

<head><style>th,td{border: thin solid black;vertical-align: middle; text-align: center;}
  table{border: thin solid black;width: 600px;margin-left: auto; margin-right: auto;}
  [colspan]{font-weight: bold;border:medium solid black;}
  </style></head>
<body><table>
  <tr>
    <th id="sno">学号</th><th id="sname">姓名</th><th id="sage">年龄</th>
  </tr>
  <tr>
    <td headers="sno">001</td><td headers="sname">张三</td><td headers="sage">20</td>
  </tr>
  <tr>
    <td headers="sno">002</td><td headers="sname">李四</td><td headers="sage">20</td>
  </tr>
  <tr>
    <td colspan="2">总计人数</td><td>2</td>
  </tr>
</table></body>

tbody元素表示构成表格主体的全体行(不包括表头行和表脚行)。习惯样式:tbody{display:table-row-group;vertical-align:middle; border-color:inherit}

thead元素用来标记表格的标题行。习惯样式:thead{display:table-header-group;vertical-align:middle; border-color:inherit}

tfoot元素用来标记组成表脚的行。习惯样式:tfoot{display:table-footer-group; vertical-align:middle;border-color:inherit}

caption元素用来为表格定义一个标题并将其与表格关联起来。习惯样式:caption{display:table-caption;text-align:center}

chap1-32.html

<!DOCTYPE html>
<html lang="en">
  <head><meta charset="UTF-8"><title>chap1-32</title>
    <style>
      thead th, tfoot th{text-align: left;background: gray;color: white}
      tbody th{text-align: right;background: lightgray;color: grey}
      caption{font-weight: bold;font-size: large;margin-bottom: 5px}
    </style>
  </head>
  <body><table>
    <caption>Results of the 2011 Fruit Survey</caption>
    <thead>
      <tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th></tr>
    </thead>
    <tfoot>
      <tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th></tr>
    </tfoot>
    <tbody>
      <tr><th>Favorite:</th><td>Apples</td><td>Green</td><td>Medium</td></tr>
      <tr><th>2nd Favorite:</th><td>Oranges</td><td>Orange</td><td>Large</td>
    </tr>
    </tbody>
</table></body></html>

colgroupcol元素能对表格按列处理。

colgroup元素的span属性规定列组应该横跨的列数。

注意:应用到colgroup上的CSS样式在具体呈现上低于直接应用到trtdth元素上的样式。

chap1-33.html

<head><style>
  thead th, tfoot th{text-align: left;background: gray;color: white}
  tbody th{text-align: right;background: lightgray;color: grey}
  caption{font-weight: bold;font-size: large;margin-bottom: 5px}
  #colgroup1{background-color: red}
  #colgroup2{background-color: green}
  </style></head>
<body><table>
  <caption>Results of the 2011 Fruit Survey</caption>
  <colgroup id="colgroup1" span="2"></colgroup>
  <colgroup id="colgroup2" span="2"></colgroup>
  <thead>
    <tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th></tr>
  </thead>
  <tfoot>
    <tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th></tr>
  </tfoot>
  <tbody>
    <tr><th>Favorite:</th><td>Apples</td><td>Green</td><td>Medium</td></tr>
    <tr><th>2nd Favorite:</th><td>Oranges</td><td>Orange</td><td>Large</td></tr>
</tbody></table></body>

col元素可以指定组中各列的样式。

chap1-34.html

<head><style>thead th, tfoot th{text-align: left;background: gray;color: white}
  tbody th{text-align: right;background: lightgray;color: grey}
  caption{font-weight: bold;font-size: large;margin-bottom: 5px}
  #colgroup1{background-color: red}
  #col3{background-color: green}
  #col4{background-color: blue}
  </style></head><body><table>
  <caption>Results of the 2011 Fruit Survey</caption>
  <colgroup id="colgroup1">
    <col id="col1and2" span="2"><col id="col3"><col id="col4">
  </colgroup>
  <thead><tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th></tr> </thead>
  <tfoot><tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th>
    </tr></tfoot>
  <tbody>
    <tr><th>Favorite:</th><td>Apples</td><td>Green</td><td>Medium</td> </tr>
    <tr><th>2nd Favorite:</th><td>Oranges</td><td>Orange</td><td>Large</td></tr>
  </tbody>
</table></body>

表单

制作一个基本的表单需要三个元素:forminputbutton元素。

form属性有actionmethodnametarget

  • action属性:提交表单时浏览器应该把从表单数据发送到何处。
  • method属性:指定表单数据发送到服务器的HTTP方法。允许的值有getpostget请求用于安全交互,同一个请求可以发送任意多次而不会产生额外作用。post请求则用于不安全交互,提交数据的行为会导致一些状态的改变。一般而言,get请求用于获取只读信息,而post请求则用于会改变应用程序状态的各种操作。

label元素可用来为表单中的每一个元素提供说明,其属性有:

  • for属性:规定label与哪个表单元素绑定。
  • form属性:规定label所属的表单。通过该属性,元素可以与文档中任何位置的表单挂钩,而不一定要放在<form></form>之间。

chap1-35.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-35</title>
    <style>
      label{
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <form name="mform" action="" method="post">
      <label for="uname">User:<input type="text" id="uname" name="uname"></label>
      <label for="upw" form="mform">Password:<input type="password" id="upw" name="upw">
      </label>
    </form>
  </body>
</html>

input元素

input元素用于收集用户输入的数据,其属性有:

  • name属性:名称;
  • form属性:所属表单;
  • disabled属性:禁用单个input元素;
  • autofocus属性:自动聚焦单个input元素;
  • type属性:指定input元素类型,具体有:

type属性值

描述
button 定义可点击按钮(多数情况下,用于通过 JavaScript 启动脚本)。
checkbox 定义复选框。
file 定义输入字段和 "浏览"按钮,供文件上传。
hidden 定义隐藏的输入字段。
image 定义图像形式的提交按钮。
password 定义密码字段。该字段中的字符被掩码。
radio 定义单选按钮。
reset 定义重置按钮。重置按钮会清除表单中的所有数据。
submit 定义提交按钮。提交按钮会把表单数据发送到服务器。
text 定义单行的输入字段,用户可在其中输入文本。默认宽度为 20 个字符。

type属性值(html5新元素)

描述
color 定义拾色器
date 定义日期字段(带有calendar控件)
datetime-local 定义日期字段(带有calendar和time控件)
month 定义日期字段的月(带有calendar控件)
week 定义日期字段的周(带有calendar控件)
time 定义日期字段的时、分、秒(带有time控件)
email 定义用于e-mail地址的文本字段
number 定义带有spinner控件的数字字段
range 定义带有slide控件的数字字段
search 定义用于搜索的文本字段
tel 定义用于电话号码的文本字段
url 定义用于URL的文本字段

text类型

定义单行文本框,其属性有:

  • list:指定为文本框提供建议值的datalist元素,其值为datalist元素的id值;
  • maxlength:设定用户可以在文本框中输入的字符的最大数目;
  • size:指定文本框中可见字符数目,默认值20
  • value:设置文本框的初始值;
  • pattern:指定一个用于输入验证的正则表达式;
  • placeholder:指定关于所需数据类型的提示;
  • readonly:将文本框设为只读以阻止用户编辑其内容;
  • required:表明用户必须输入一个值,否则无法通过输入验证。

chap1-36.html (maxlength size value placeholder readonly required)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-36</title>
    <style>
      label{font-weight: bold;}
    </style>
  </head>
  <body>
    <form method="post" action="">
      <label for="sno">student number:<input type="text" name="sno" id="sno" value="1505071" maxlength="10" placeholder="Your ID" required></label><br>
      <label for="sname">student name:<input type="text" name="sname" id="sname" value="zhangsan" size="30" readonly></label><br>
      <input type="submit" name="login" value="OK">
    </form>
  </body>
</html>

pattern属性规定用于验证输入字段的模式。模式指的是正则表达式,例如:

<input type="text" name="sno" pattern="[A-Za-z0-9]{4,6}">

方括号用于查找某个范围内的字符:

  • [abc]: 查找方括号之间的任何字符;

  • [^abc]:查找任何不在方括号之间的字符。

量词

  • n{X}:匹配包含X个n的序列的字符串;
  • n{X,Y}:匹配包含X至Y个n的序列的字符串;
  • n{X,}:匹配包含至少X个n的序列的字符串。

list属性可以生成数据列表,但要与datalist元素配套使用。

datalist元素可以用来提供一组值,提供给用户选择的值各用一个option元素指定。

option元素的属性:

  • disabled:规定此选项在首次加载时被禁用;
  • selected:规定选项在首次加载时表现为选中状态;
  • label:定义选项的标注;
  • value:定义送往服务器的选项值。

chap1-37.html (list pattern)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-37</title>
  </head>
  <body>
    <form method="post" action="">
      <p>name:<input type="text" name="uname" pattern="[A-Za-z0-9]{4,6}"></p>
      <p>fruit:<input type="text" name="fave" list="fruitlist"></p>
      <input type="submit" name="login" value="OK">
    </form>
    <datalist id="fruitlist">
      <option value="Apples" label="Lovely Apples"/>
      <option value="Oranges">Refreshing Oranges</option>
      <option value="Cherries"/>
    </datalist>
  </body>
</html>

password类型

生成密码框,用户输入的字符在这种文本框中显示为星号(*)之类的掩饰字符。其属性与text类型一致,且用法相同。

chap1-38.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-38</title>
  </head>
  <body>
    <form method="post" action="">
      <p>name:<input type="text" name="uname" pattern="[A-Za-z0-9]{4,6}" title="A-Z, a-z, or 0-9 are allowed, and the length must be between 4 and 6"></p>
      <p>password:<input type="password" name="upw"></p>
      <input type="submit" name="login" value="OK">
    </form>
  </body>
</html>

button类型

submit类型:提交表单,其属性有:

  • formaction:覆盖form元素的action属性,另行指定表单将要提交到的URL。
  • formmethod:覆盖form元素的method属性。
  • formtarget:覆盖form元素的target属性。
  • reset类型:重置表单;
  • button类型:表示按钮,没有具体语义。HTML5推荐使用button元素,与 <input type="button">相比,button元素提供了更为强大的功能和更丰富的内容。

chap1-39-1.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-39-1</title>
    <script>
      function dp() {
        var form=document.getElementById("my_form");
        alert(form.uname.value);
      }
    </script>
  </head>
  <body>
    <form method="post" action="" id="my_form">
      <p>name:<input type="text" name="uname" pattern="[A-Za-z0-9]{4,6}" title="A-Z, a-z, or 0-9 are allowed, and the length must be between 4 and 6"></p>
      <p>password:<input type="password" name="upw"></p>
      <input type="submit" name="login" value="OK" formaction="chap1-1.html" formtarget="_blank">
      <input type="reset">
      <input type="button" name="output" value="print" onclick="dp()">
    </form>
</body></html>

button元素

autofocus属性:规定当页面加载时按钮应当自动地获得焦点。

disabled属性:规定应该禁用该按钮。

form属性:规定按钮属于一个表单。

formaction属性:覆盖form元素的action属性,与type=submit配合使用。

formmethod属性:覆盖form元素的method属性,与type=submit配合使用。

formtarget属性:覆盖form元素的target属性,与type=submit配合使用。

name属性:规定按钮名称。

type属性:buttonsubmitreset三种类型。

value属性:规定按钮的初始值。

chap1-39.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-39</title>
  </head>
  <body>
    <form method="post" action="">
      <p>name:<input type="text" name="uname" pattern="[A-Za-z0-9]{4,6}" title="A-Z, a-z, or 0-9 are allowed, and the length must be between 4 and 6"></p>
      <p>password:<input type="password" name="upw"></p>
      <input type="submit" name="login" value="OK" formaction="chap1-1.html" formtarget="_blank">
      <button type="submit" formaction="chap1-2.html" formtarget="_self">chap1-2</button>
      <input type="reset">
    </form>
  </body>
</html>

checkboxradio类型

checkbox用于生成复选框,其属性除了具有input元素属性外,另有:

  • checked:规定当页面加载时该选项自动被选中;
  • required:表示用户必须勾选该复选框;
  • value:设定在复选框呈勾选状态时提交给服务器的数据值,默认为on

注意:各选项name属性不能相同!建议value值取相同值ontrue等。

radio用于生成单选按钮,其属性与checkbox相同

注意:各选项name属性必须相同,value值不能相同!

chap1-40.html

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8">
    <title>chap1-40</title>
  </head>
  <body>
    <form action="" method="post">
      <p>感兴趣的书籍种类:<input type="checkbox" name="html" value="true">HTML5
        <input type="checkbox" name="CSS" checked>CSS
        <input type="checkbox" name="JavaScript" required>JavaScript</p>
      <p>性别:<input type="radio" name="sex" value="man" checked>男
        <input type="radio" name="sex" value="woman">女</p>
    </form>
  </body>
</html>

image类型

生成图像按钮,点击图像按钮会导致浏览器提交表单。其属性有:

  • formactionformmethodformtargetbutton元素
  • src:指定要显示的图像的URL
  • widthheight:以像素为单位设置图像的宽度和高度(不设置的话图像将以其本身的宽度和高度显示)

chap1-41.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-41</title>
  </head>
  <body>
    <form action="chap1-1.html" method="post">
      <p>Name:<input type="text" name="user"></p>
      <p><input type="image" src="pic/check.jpg" name="submit" width="50" height="50"></p>
    </form>
  </body>
</html>

file类型

该类型可以在提交表单时将文件上传到服务器,除input元素支持的属性外,还有:

  • accept:指定接受的MIME类型,常用MIME类型有:

    类型/子类型 扩展名 类型/子类型 扩展名 类型/子类型 扩展名
    application/msword doc application/pdf pdf application/vnd.ms-excel xls
    application/vnd.ms-powerpoint ppt application/vnd.ms-works wps application/zip zip
    image/bmp bmp image/jpeg jpeg image/tiff tif
    image/gif gif video/mpeg mpeg text/plain txt
  • multiple:一次可上传多个文件。

  • required:表明用户必须为其提供一个值。

hidden类型

生成隐藏数据项。

chap1-42.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-42</title>
  </head>
  <body>
    <form action="chap1-1.html" method="post">
      <p><input type="hidden" name="pageid" value="2"></p>
      <p><input type="file" name="filedata" accept="image/jpeg,application/msword" multiple></p>
      <p><input type="submit"></p>
    </form>
  </body>
</html>

color类型

生成颜色选择器。Chrome、Opera和Safari最新版本均支持,其它浏览器Firefox、IE暂不支持

chap1-43.html

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8">
    <title>chap1-43</title>
  </head>
  <body>
    <input type="color" id="color" style="display: none">
    <button id="btn">弹出色盘</button>
  </body>
</html>
<script type="text/javascript">
  document.getElementById('btn').onclick=function () {
    document.getElementById('color').click();
  }
  document.getElementById('color').onchange=function () {
    document.body.style.background=this.value;
  }
</script>

日期和时间选择器

date - 选择日、月、年

month - 选择月、年

week - 选择周、年

time - 选择时间(时、分)

datetime-local -选择时间、日期、月、年(本地时间)

chap1-44.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-44</title>
  </head>
  <body>
    <p>Date:<input type="date" name="user_date"></p>
    <p>Datetime:<input type="datetime-local" name="user_datetime"></p>
    <p>Month:<input type="month" name="user_month"></p>
    <p>Week:<input type="week" name="user_week"></p>
    <p>Time:<input type="time" name="user_time"></p>
  </body>
</html>

emailurlsearch

email用于应该包含电邮地址的输入字段,当提交表单时会自动验证;

url用于应该包含 URL 地址的输入字段,会在提交表单时对 url 字段的值自动进行验证。

search用于生成一个单行文本框,供用户输入搜索用词。浏览器可以设法用这种文本框的外观表明它是用来获取搜索用词的。chrome的做法是一旦用户输入了内容,就再显示一个取消图标。

chap1-45.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-45</title>
  </head>
  <body>
    <form method="post" action="chap1-1.html">
      <p>e-mail: <input type="email" name="user_email"></p>
      <p>home page:<input type="url" name="user_url"></p>
      <p>search:<input type="search" name="msearch" placeholder="请输入关键词"></p>
      <p><input type="submit"></p>
    </form>
  </body>
</html>

telnumberrange

tel用于应该包含电话号码的输入字段。

number用于包含数字值的输入字段,其属性有:

  • list指定为文本框提供建议值的datalist元素,其值为datalist元素的id值;
  • minmax设定可接受的最小值和最大值;
  • step指定上下调节数值的步长;
  • value 设定默认值

range用于应该包含指定范围值的输入字段,显示为滑块。属性同number

chap1-46.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-46</title>
  </head>
  <body>
    <form action="chap1-1.html" method="post">
      <p>telephone:<input type="tel" name="utel" pattern="[0-9]{11}"></p>
      <p>points:<input type="number" name="mpoint" min="1" max="9" step="2" value="5"> </p>
      <p>color:</p>
      <p>red&#160;<input type="text" id="r" name="r" size="3"><input type="range" id="ured" min="0" max="255"></p>
      <p><input type="submit"></p>
    </form>
  </body>
</html>
<script type="text/javascript">
  document.getElementById('ured').onchange=function () {
    document.getElementById('r').value=this.value;
  }
</script>

其他表单元素

元素 说明
select 生成一个选项列表供用户选择
optgroup select元素中的选项编组
textarea 获取用户输入的多行文字
output 表示计算结果

select元素

select元素用于生成一系列选项供用户选择。其属性有:

  • namedisabledformautofocusrequired,与input元素类似。
  • size属性:用来设定要显示给用户的选项数目。
  • multiple属性:允许用户选择多个选项。

提供给用户的选项由option元素定义。

chap1-47.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-47</title>
  </head>
  <body>
    <form action="chap1-1.html" method="post">
      <p>fruit:<input type="text" name="fruit" list="fruitlist"></p>
      <p>color:<select name="favecolor">
        <option value="red">red color</option>
        <option value="green">green color</option>
        <option value="orange">orange color</option>
        <option value="yellow">yellow color</option>
        </select></p>
      <input type="submit" name="login" value="OK">
    </form>
    <datalist id="fruitlist">
      <option value="Apples" label="Lovely Apples"/>
      <option value="Oranges">Refreshing Oranges</option>
      <option value="Cherries"/>
    </datalist>
</body></html>

optgroup元素

optgroup元素用于对option元素进行编组。其属性有:

  • label属性:用来为整组选项提供一个小标题。
  • disabled属性:用来阻止选择组内的任何选项。

chap1-48.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-48</title>
  </head>
  <body>
    <form action="chap1-1.html" method="post">
      <p>fruit:<select name="fave">
        <optgroup label="Top Choices">
          <option value="apples" label="Apples">Apples</option>
          <option value="oranges" label="Oranges">Oranges</option>
        </optgroup>
        <optgroup label="Others">
          <option value="cherries" label="Cherries"/>
          <option value="bananas" label="Bananas"/>
        </optgroup>
        </select></p>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

textarea元素

textarea元素用于生成多行文本框。其属性有:

  • namedisabledformreadonlymaxlengthautofocusrequiredplaceholder
  • rowscols属性:设置其大小。

chap1-49.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-49</title>
  </head>
  <body>
    <form action="" method="post">
      <p>Reason:<textarea rows="4" cols="50" name="reason">Tell us why this is your favorite fruit.</textarea></p>
    </form>
  </body>
</html>

output元素

output元素表示计算的结果。其属性有:nameformfor

chap1-50.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-50</title>
  </head>
  <body>
    <form onsubmit="return false" oninput="res.value=quant.value*price.value">
      <input type="number" id="quant" name="quant">*
      <input type="number" id="price" name="price">=
      <output for="quant name" name="res"></output>
    </form>
  </body>
</html>

fieldset元素

fieldset元素可以将一些表单元素组织在一起,其属性有:nameformdisabled。习惯样式fieldset{display:block;margin-start:2px; margin-end:2px; padding-before:0.35em; padding-start:0.75em;padding-end:0.75em; padding-after:0.625em; border:2px groove;}

Legend元素可以为每一个表单分组提供说明。

chap1-51.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-51</title>
  </head>
  <body>
    <form onsubmit="return false" oninput="res.value=quant.value*price.value">
      <fieldset>
        <legend>Price Calculator</legend>
        <input type="number" id="quant" name="quant">*
        <input type="number" id="price" name="price">=
        <output for="quant name" name="res"></output>
      </fieldset>
    </form>
  </body>
</html>

嵌入内容

元素 说明
img 在HTML文档中嵌入图像
maparea 在嵌入图像上创建客户端分区响应图
iframe 嵌入另一张HTML文档
embed 通过插件嵌入内容
object 创建浏览上下文
audiovideosource 不通过插件嵌入音频和视频

img元素

img元素允许我们在HTML文档里嵌入图像。其属性有:

  • src属性:指定图像的URL。

  • alt属性:定义img元素的备用内容。

  • widthheight属性:指定图像尺寸(单位是像素)。

  • ismap属性:创建一个服务器分区响应图,即在图像上点击的位置会附加到URL上发送到服务器,例如:http://.../location.html?10,4

    注释:只有当 <img>元素属于带有有效 href 属性的<a>元素的后代时,才允许ismap属性。

chap1-52.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-52</title>
  </head>
  <body>
    <p>The picture of apples</p>
    <a href="location.html">
      <img src="pic/apple.jpg" alt="favorite fruit" width="500" height="350" ismap/>
    </a>
  </body>
</html>

location.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>The coordinate of the point</title>
  </head>
  <body>
    <p>The X-coordinate is <span style="font-weight: bold" id="xco"></span></p>
    <p>The Y-coordinate is <span style="font-weight: bold" id="yco"></span></p>
  </body>
</html>
<script>
  var coords=window.location.href.split("?")[1].split(",");
  /* JS中的location.href有很多种用法,主要如下:
     self.location.href="/url" 当前页面打开URL页面
     location.href="/url" 当前页面打开URL页面
     windows.location.href="/url" 当前页面打开URL页面
  */
  document.getElementById("xco").innerHTML=coords[0];
  document.getElementById("yco").innerHTML=coords[1];
  // innerHTML在JS是双向功能:获取对象的内容或向对象插入内容;
</script>
  • usemap属性:创建一个客户端分区响应图,通过点击某张图像上的不同区域让浏览器导航到不同的URL上。这一过程不需要通过服务器引导,因此需要使用元素来定义图像上的各个区域以及它们所代表的行为。

maparea元素

map元素是客户端分区响应图的关键元素。map元素包含一个或多个area元素,它们各自代表了图像上可被点击的一块区域。area元素属性有:

  • hreftarget(参见a元素)、alt(参见img元素)、media(参见style元素)、reltype(参见link元素)

  • shape属性和coords属性:标明用户可以点击的各个图像区域。shapecoords属性是共同起作用的,coords属性的意思根据shape属性的值而定。

    shape coords属性的性质
    rect 代表一个矩形区域。coords属性必须由4个整数组成,中间用逗号分隔。 “x左上,y左上,x右下,y右下”,图像左上角坐标是(0,0)
    circle 代表一个圆形区域。coords属性必须由3个用逗号分隔的整数组成。 “x圆心,y圆心,圆的半径”
    poly 代表一个多边形。coords属性必须至少包含6个用逗号分隔的整数,每一对数字各代表多边形的一个顶点坐标。
    default 这个值的意思是默认区域,即覆盖整张图片。不需要提供coords

chap1-53.html

<body>
  <p>请点击图像上的星球,把它们放大。</p>
  <img src="pic/eg_planets.jpg" border="0" usemap="#planetmap">
  <map name="planetmap">
    <area shape="circle" coords="180,139,14" href="venus.html" target="_blank">
    <area shape="circle" coords="129,161,10" href="mercur.html" target="_blank">
    <area shape="rect" coords="0,0,110,260" href="sun.html" target="_blank">
  </map>
</body>

mercur.html

<body><p><img src="pic/mercury.jpg" height="575" width="615"></p></body>

venus.html

<body><p><img src="pic/venus.jpg" height="600" width="600"></p></body>

sun.html

<body><p><img src="pic/venus.jpg" height="600" width="600"></p></body>

iframe元素

iframe元素允许我们在HTML文档里嵌入另一张文档。其属性有:

  • src属性:指定文档的URL。

  • srcdoc属性:规定页面的HTML内容。

  • widthheight属性:定义iframe的宽度和高度。

  • scrolling属性:规定是否在iframe中显示滚动条,其值有yes/no/auto

  • sandbox属性:启用一系列对iframe中内容的额外限制,其值有:

    说明
    空字符串 ("") 应用以下所有的限制
    allow-forms 启用表单
    allow-scripts 启用脚本
    allow-same-origin 允许iframe里的内容被视为与文档其余部分拥有同一个来源位置
    allow-top-navigation 允许iframe内容从包含文档导航(加载)内容。
  • frameborder属性:规定是否显示框架周围的边框,其值有:10

chap1-54.html

<body>
  <header>
    <h1>Things I Like</h1>
    <nav>
      <ul>
        <li><a href="chap1-2.html" target="myframe">chap1-2</a></li>
        <li><a href="chap1-28.html" target="myframe">chap1-28</a></li>
      </ul>
    </nav>
  </header>
  <iframe srcdoc="<p>hello world!</p>" src="chap1-1.html" name="myframe" width="60%" height="400" scrolling="yes" sandbox="allow-same-origin" frameborder="1"></iframe>
</body>

objectembed元素

objectembed元素通常用于添加插件,从而扩展浏览器功能。

embed元素属性有:

  • src属性:嵌入内容的URL;
  • type属性:嵌入内容的MIME类型;
  • widthheight属性:设置嵌入内容的宽度和高度。

object元素属性有:

  • typewidthheight属性同embed元素;
  • data属性:定义引用对象数据的 URL。

chap1-55.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap1-55</title>
  </head>
  <body>
    <embed src="flash/chap1-55-1.swf" type="application/x-shockwave-flash" width="600" height="400"></embed>
  <object data="flash/chap1-55-2.swf" type="application/x-shockwave-flash" width="600" height="400"></object>
  </body>
</html>

使用多媒体

video元素可以在网页中嵌入视频内容,其属性有:

  • controls属性:如果出现该属性,则向用户显示控件,比如播放按钮,其值为controls

  • widthheight属性:设置视频播放器的宽度和高度;

  • loop属性:如果出现该属性,则当媒介文件完成播放后再次开始播放,其值为loop

  • preload属性:如果出现该属性,则视频在页面加载时进行加载,并预备播放。

  • autoplay属性:如果出现该属性,则视频在就绪后马上播放。

  • src属性:要播放的视频的 URL。目前浏览器支持的视频格式有:

    格式 说明 支持
    WebM 带有 VP8 视频编码和 Vorbis 音频编码的 WebM 文件 Chrome、Opera、Firefox
    Ogg 带有 Theora 视频编码和 Vorbis 音频编码的 Ogg 文件 Chrome、Opera、Firefox
    MP4 带有 H.264 视频编码和 AAC 音频编码的 MPEG 4 文件 IE、Chrome、Safari
  • source元素为媒介元素(比如 <video><audio>)定义媒介资源。允许您规定可替换的视频/音频文件供浏览器根据它对媒体类型或者编解码器的支持进行选择。其属性有:

    • src属性:规定媒体文件的 URL;
    • type属性:规定媒体资源的 MIME 类型,用于视频其值有:video/oggvideo/mp4video/webm;用于音频其值有:audio/oggaudio/mpeg

chap1-56.html

<body>
  <video src="video/chap1-56.ogg" controls autoplay width="600" height="400">Video cannot be displayed</video>
  <video controls autoplay width="600" height="400">
    <source src="video/chap1-56.ogg">
    <source src="video/chap1-56.mp4">
  </video>
</body>

audio元素可以在网页中嵌入音频内容,其属性有:

  • controlsloopautoplaypreload属性:同video
  • src属性:要播放的音频的URL。

chap1-57.html

<body>
  <audio controls autoplay loop>
    <source src="audio/horse.ogg" type="audio/ogg">
    <source src="audio/horse.mp3" type="audio/mpeg">
  </audio>
</body>

CSS 3

CSS概述

CSS(层叠样式表)用来规定HTML文档的呈现形式(外观和格式编排)。

问题 解决方案
定义样式 使用属性/值声明
将样式直接应用于元素 style全局属性创建元素内嵌样式
创建可用于多个元素的样式 使用style元素,编写一个选择器和一组样式声明
创建可用于多个html文档的样式 创建一个外部样式表文件,并用link元素引用它
确定元素将使用什么样式属性 对样式来源使用层叠规则,同级样式发生冲突时计算并比较样式的具体程度
改变正常的样式层叠次序 使用重要样式
使用父元素的样式属性 使用属性继承
根据一条属性确定另一条属性的值 使用相对度量单位

定义样式

CSS样式由一条或多条以分号隔开的样式声明组成,每条声明包含着一个CSS属性和该属性的值,二者以冒号分隔。

第一章涉及到的样式说明

属性 说明 属性 说明
background-color 设置元素的背景颜色 border 设置围绕元素的边框
color 设置元素的前景颜色 font-size 设置元素文字的字号
font-weight 设置元素文字的粗细 font-style 设置元素文字的风格
font-family 设置元素文字的字体 width 设置元素宽度
height 设置元素高度 margin 设置元素内容所有外边距的宽度
padding 设置元素内容与边框之间的间距 text-align 设置元素文字的水平对齐方式
text-decoration 设置元素文字的装饰效果 display 设置元素显示框的类型

使用元素内嵌样式

把样式应用到元素上最直接的方式是使用全局属性style

chap2-1.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-1</title>
  </head>
  <body>
    <p style="background-color: blue; color: white;text-align: center;font-weight: bolder;font-style: italic;font-size: larger;margin: 50px 20px 50px 20px;padding: 10px 0px;border: dotted medium red">Nanjing Foresty University</p>
  </body>
</html>

使用文档内嵌样式

style元素定义文档内嵌样式。

chap1-9.html

<style type="text/css">
  a{
    background: gray;
    color: white;
    padding: 10px;
  }
</style>

使用外部样式表

如果有一套样式要用于多个HTML文档,则单独创建一个独立的样式表文件,以.css为文件扩展名。然后HTML文档利用link元素将样式表文件导入其中。

chap1-10.css

a{ background: grey; color: white; padding: 10px;}

chap1-10.html

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="css1/chap1-10.css">
  </head>
  <body>
    <a href="chap1-1.html">chap1-1.html</a>
  </body>
</html>

可以用@import语句将样式从一个样式表导入另一个样式表。

chap2-2.css

@import "../../chap1/css1/chap1-10.css";
p{font-weight: bold; font-size: x-large;}

chap2-2.html

<html lang="en">
  <head>
    <link rel="stylesheet" type="text/css" href="css2/chap2-2.css">
  </head>
  <body>
    <a href="../chap1/chap1-1.html">chap1-1.html</a>
    <p><a href="../chap1/chap1-2.html">chap1-2.html</a></p>
  </body>
</html>

样式的层叠和继承

样式层叠的次序:

  1. 元素内嵌样式;
  2. 文档内嵌样式;
  3. 外部样式。

把样式属性值标记为!important,可以改变正常的层叠次序。

chap2-3.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-3</title>
    <style type="text/css">
      a{
        color: blue !important;
      }
    </style>
  </head>
  <body>
    <p><a style="color: red; font-size:larger; text-decoration: none" href="chap2-1.html">chap2-1.html</a></p>
    <p><a href="chap2-2.html">chap2-2.html</a> </p>
  </body>
</html>

如果浏览器在直接相关的样式中找不到某个属性的值,就会求助于继承机制,使用父元素的这个样式属性值。但并非所有CSS属性均可继承,一般来说:

  • 与元素外观(文字颜色、字体等)相关的样式会被继承;
  • 与元素在页面上的布局相关的样式不会被继承;
  • 在样式中使用inherit可强行实施继承。

chap2-4.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-4</title>
    <style type="text/css">
      p{
        color: white;
        background: grey;
        border: medium solid black;
      }
      span{
        border:inherit;
      }
    </style>
  </head>
  <body>
    <p>I like <span>apples</span> and oranges.</p>
  </body>
</html>

CSS颜色函数

函数 说明 示例
rgb(r, g, b) 用RGB模型表示颜色 color:rgb(112,128,144)
rgba(r, g, b, a) 用RGB模型表示颜色,外加一个用于表示透明度的a值(0:全透明,1:不透明) color:rgba(112,128,144,0.4)
hsl(h, s, l) 用HSL模型(色相hue、饱和度saturation、明度lightness)表示颜色 color:hsl(110,100%,22%)
hsla(h, s, l, a) 用HSL模型表示颜色,外加一个用于表示透明度的a值 color:hsla(110,100%,22%,0.4)

CSS中的长度

CSS规定了2种类型的长度单位,一种是绝对单位,另一种是与其他属性挂钩的相对单位。

CSS支持5种绝对单位:

单位标识符 说明 单位标识符 说明
in 英寸(1in=2.54cm) cm 厘米
mm 毫米 pt 磅(1pt=1/72in)
pc pica(1pica=12pt)

CSS支持的相对单位:

单位标识符 说明 单位标识符 说明
em 与元素字体尺寸挂钩 ex 与元素字体的“x高度”挂钩(1ex=0.5em)
rem 与根元素(HTML元素)的字号挂钩 px CSS像素
% 另一属性的值的百分比

使用%需注意:

  • 并非所有属性都能用这个单位;
  • 对于能用%的属性,%挂钩的其他属性各不相同,例如,对于font-size属性,挂钩的是元素继承到的font-size值;对于width属性,挂钩的则是元素的包含块的宽度。

chap2-5.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-5</title>
    <style type="text/css">
      html{
        font-size: 0.2in;
      }
      p{
        background: rgb(80,80,80);
        color: white;
        font-size: 2rem;
        height: 2em;
        border: solid medium black;
        width: 60%;
      }
    </style>
  </head>
  <body>
    <p>I like <span>apples</span> and oranges</p>
    <p style="font-size: 200%">I also like mangos and cherries.</p>
  </body>
</html>

盒模型

CSS中的一个基本概念是盒模型。元素会在页面中占据一个矩形区域,该区域就是元素的盒子,由4部分组成:

CSS选择器

CSS选择器的作用是找出某类元素,以便使用style元素或者外部样式表对这类元素设置样式。

问题 解决方案
选择所有元素 使用通用选择器
根据类型选择元素 使用类型选择器
根据全局属性class的值选择元素 使用类选择器
根据全局属性id的值选择元素 使用id选择器
基于属性选择元素 使用属性选择器
同时匹配多个选择器 选择器之间用逗号隔开
选择元素的后代元素 选择器之间用空格隔开
选择元素的子元素 使用>选择器
选择兄弟元素 使用+~选择器
选择文本块的首行文本 使用::first-line选择器
选择文本块的首字母 使用::first-letter选择器
在元素之前或之后插入内容 使用:before:after选择器
向元素插入数值内容 使用counter函数
选择文档中的根元素 使用:root选择器
选择子元素 使用:first-child:last-child:only-child:only-of-type选择器
选择指向索引处的子元素 使用:nth-child:nth-last-child:nth-of-type、或:nth-last-of-type选择器
选择启用或禁用的元素 使用:enabled:disabled选择器
选择被勾选的单选按钮或复选框 使用:checked选择器
选择默认元素 使用:default选择器
根据输入验证选择元素 使用:valid:invalid选择器
选择指定范围的输入元素 使用:in-range:out-of-range选择器
根据是否允许使用必需属性选择输入元素 使用:required:optional选择器
选择超链接 使用:linked:visited选择器
选择鼠标当前悬停在其上的元素 使用:hover选择器
选择当前被用户激活的元素 使用:active选择器
选择获得焦点的元素 使用:focus选择器
选择不匹配某个选择器的元素 使用否定选择器
选择基于lang全局属性值的元素 使用:lang选择器

CSS基本选择器

通用选择器

匹配文档中的所有元素,包括htmlbody元素。

格式:*

chap2-6.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-6</title>
    <style type="text/css">
      *{
        border: thin black solid;
        padding:4px;
      }
    </style>
  </head>
  <body>
    <a href="chap2-1.html">chap2-1.html</a>
    <p>I like <span>apples</span> and oranges.</p>
  </body>
</html>

类型选择器

匹配文档中该元素的所有实例。

格式:元素类型

chap2-7.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-7</title>
    <style type="text/css">
      a{
        border: thin black solid;
        padding: 4px;
      }
    </style>
  </head>
  <body>
    <a href="chap2-1.html">chap2-1.html</a>
    <p>I like <span>apples</span> and oranges.</p>
  </body>
</html>

类选择器

采用全局属性class匹配指定类的元素。

格式为:

  • *.类名
  • .类名
  • 元素类型.类名

chap2-8.html

<head>
  <meta charset="UTF-8">
  <title>chap2-8</title>
  <style type="text/css">
    .class1{
      border: dotted medium black;
      padding: 4px;
    }
    span.class2{
      border: solid thin red;
    }
  </style>
</head>
<body>
  <a class="class1" href="chap2-1.html">chap2-1.html</a>
  <p class="class1">I like <span class="class2">apples</span> and oranges.</p>
</body>

id选择器

根据全局属性id的值选择元素。

格式为:

  • 元素类型#id值
  • #id值

chap2-9.html

<head>
  <meta charset="UTF-8">
  <title>chap2-9</title>
  <style type="text/css">
    #myanchor{
      border: dotted medium black;
      padding: 4px;
      color: black;
    }
    span#mapple{
      border: solid thin red;
    }
  </style>
</head>
<body>
  <a id="myanchor" href="chap2-1.html">chap2-1.html</a>
  <p>I like <span id="mapple">apples</span> and oranges. </p>
</body>

属性选择器

能基于属性的不同方面匹配属性。

格式为:

  • [条件]
  • 元素类型[条件]
条件 说明
[attr] 选择定义attr属性的元素
[attr="val"] 选择定义attr属性,且属性值为val的元素
[attr^="val"] 选择定义attr属性,且属性值以字符串val打头的元素
[attr$="val"] 选择定义attr属性,且属性值以字符串val结尾的元素
[attr*="val"] 选择定义attr属性,且属性值包含字符串val的元素
[attr~="val"] 选择定义attr属性,且属性值具有多个值,其中一个为字符串val的元素
`[attr ="val"]` 选择定义attr属性,且属性值等于val或以val-开头的所有元素

chap2-10.html

<head>
  <meta charset="UTF-8">
  <title>chap2-10</title>
  <style type="text/css">
    [href]{color: red;font-size: 2em}
    a[href="chap2-2.html"]{color: green}
    [href^="chap1"]{color: blue}
    [href$="com"]{color: black}
    [href*="jd"]{color:orange}
    p[class~="important"]{color: violet}
    p[lang|="en"]{background: yellow}
  </style>
</head>
<body>
  <a href="chap2-1.html">chap2-1.html</a><br>
  <a href="chap2-2.html">chap2-2.html</a><br>
  <a href="chap1-1.html">chap1-1.html</a><br>
  <a href="http://www.sohu.com">sohu</a><br>
  <a href="http://www.jd.com">jd</a><br>
  <p class="important warning">This is a paragraph.</p>
  <p lang="en">Hello!</p>
  <p lang="en-us">Greeting!</p>
  <p lang="zh">nihao!</p>
</body>

CSS复合选择器

并集选择器

创建由逗号分隔的多个选择器可以将样式应用到单个选择器匹配的所有元素。

格式:选择器1,选择器2,选择器3,…

chap2-11.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-11</title>
    <style type="text/css">
      a,p[lang|="en"]{color: red;border: dotted medium black}
    </style>
  </head>
  <body>
    <a href="http://www.jd.com">jd</a><br>
    <p class="important warning">This is a paragraph.</p>
    <p lang="en">Hello!</p>
    <p lang="en-us">Greeting!</p>
    <p lang="zh">nihao!</p>
  </body>
</html>

后代选择器

用于选择包含在其他元素中的元素。

格式:第一个选择器 第二个选择器

chap2-12.html

<head>
  <meta charset="UTF-8">
  <title>chap2-12</title>
  <style type="text/css">
    p span{border: dotted medium black;color: red}
    #mypara span{border: solid medium black;color: blue}
    .class1 span{border: dashed thin black;color: green}
  </style>
</head>
<body>
  <p>I like <span>apples</span> and oranges.</p>
  <p id="mypara">I also like <span>mangos</span> and cherries.</p>
  <p class="class1">I like <span>apples</span> and oranges.</p>
</body>

子代选择器

与后代选择器类似,选择匹配元素中的直接后代。

格式:第一个选择器>第二个选择器

chap2-13.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-13</title>
    <style type="text/css">
      table{border: thin black solid}
      tr>th{border: medium red dotted}
      tr td{border: thin black solid}
    </style>
  </head>
  <body>
    <table>
      <tr><th>Name</th><th>City</th></tr>
      <tr><td>Zhangsan</td><td>Nanjing</td></tr>
      <tr><td>Lisi</td><td>Shanghai</td></tr>
    </table>
  </body>
</html>

相邻兄弟选择器

可选择紧接在某一元素后的元素,且二者有相同父元素。

格式:第一个选择器+第二个选择器

普通兄弟选择器

可选择跟在(不一定是紧跟)某一元素后的元素,且二者有相同父元素。

格式:第一个选择器~第二个选择器

chap2-14.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-14</title>
    <style type="text/css">
      h1+p{border: solid medium black}
      h2~p{border: dotted medium black}
    </style>
  </head>
  <body>
    <h1>This is a heading.</h1>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <h2>This is a heading.</h2>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
  </body>
</html>

CSS伪元素选择器

::first-line选择器匹配文本块的首行;

::first-letter选择器匹配文本块的首字母;

:before选择器在选中元素的内容之前插入内容;

:after选择器在选中元素的内容之后插入内容。

chap2-15.html

<head>
  <style type="text/css">
    ::first-line{background-color: grey;color: white}
    ::first-letter{font-size:15pt;font-weight: bolder;font-style: italic;padding: 4px}
    a{border: dotted medium black;color: black;text-decoration: none}
    a:before{content: "Click here to ";color: red}
    a:after{content: "!";color: red}
  </style>
</head>
<body>
  <p>In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide. It principally occurs through the process of photosynthesis, which uses light as its source of energy, but it also occurs through chemosynthesis, which uses the oxidation or reduction of inorganic chemical compounds as its source of energy</p>
  <a href="chap2-1.html">chap2-1.html</a>
</body>

CSS计数器

创建计数器,需要使用:

  • counter-reset属性:利用这个属性,计数器可以设置或重置为任何值,可以是正值或负值。如果没有提供 number,则默认为 0。例如:counter-reset: mycount 0;

  • counter:计数器,在CSS中counter()只能被使用在content属性上。语法为:counter(name,list-style-type)

    list-style-type 说明 list-style-type 说明
    none 无标记 disc 实心圆,默认
    circle 空心圆 square 实心方块
    decimal 数字 decimal-leading-zero 0开头的数字标记(01,02,…)
    lower-roman 小写罗马数字(i, ii, …) upper-roman 大写罗马数字(I, II,…)
    lower-alpha 小写英文字母 upper-alpha 大写英文字母
  • counter-increment属性:设置计数器增量,默认为1。例如:counter-increment: mycount 2

chap2-16.html

<head>
  <meta charset="UTF-8">
  <title>chap2-16</title>
  <style type="text/css">
    body{
      counter-reset: mycount 0;
    }
    p:before{
      content: counter(mycount,lower-alpha)". ";
      counter-increment: mycount 2;
    }
  </style>
</head>
<body>
  <h1>Fruits I like</h1>
  <p>I like apples and oranges.</p>
  <p>I also like mangos and cherries.</p>
</body>

结构性伪类选择器

使用结构性伪类选择器能够根据元素在文档中的位置选择元素。这类选择器都有一个冒号字符前缀。

:root选择器匹配文档中的根元素(html元素)。

chap2-17.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-17</title>
    <style type="text/css">
      :root{
        border: solid medium black;
        padding:10px;
      }
    </style>
  </head>
  <body>
    <h1>Fruits I like</h1>
    <p>I like apples and oranges.</p>
    <p>I also like mangos and cherries.</p>
  </body>
</html>

子元素选择器匹配直接包含在其他元素中的单个元素。

:first-child:选择元素的第一个子元素;

:last-child:选择元素的最后一个子元素;

:only-child:选择元素的唯一子元素;

:only-of-type:选择元素指定类型的唯一子元素。

chap2-18.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-18</title>
    <style type="text/css">
      body>:first-child{border: solid medium black}
      body>:last-child{border: solid medium red}
      p>:only-child{background-color: orange}
      body>:only-of-type{background-color: blue}
    </style>
  </head>
  <body>
    <h1>Fruits I like</h1>
    <p>I like <span>apples</span> and <span>oranges.</span></p>
    <p>I also like <span>mangos</span> and cherries.</p>
  </body>
</html>

:nth-child选择器:匹配属于其父元素的第N个子元素,不论元素的类型。

选择器 说明
:nth-child(N) 选择父元素的第N个子元素
:nth-last-child(N) 选择父元素的倒数第N个子元素
:nth-of-type(N) 选择父元素定义类型的第N个子元素
:nth-last-of-type(N) 选择父元素定义类型的倒数第N个子元素

chap2-19.html

<head>
  <meta charset="UTF-8">
  <title>chap2-19</title>
  <style type="text/css">
    body>:nth-child(2){border: thin black solid}
    body>:nth-last-child(1){border: thin black dotted}
    h3:nth-of-type(odd){background-color: rgba(255,0,0,0.5)}
    h3:nth-of-type(even){background-color: rgba(0,0,255,0.5)}
    h4:nth-last-of-type(2){background-color: rgba(0,255,0,0.5)}
  </style>
</head>
<body>
  <a href="chap2-1.html">chap2-1.html</a>
  <p>I like <span>apples</span> and oranges.</p>
  <a href="chap2-2.html">chap2-2.html</a>
  <h3>this is the first paragraph</h3>
  <h3>this is the second paragraph</h3>
  <h3>this is the third paragraph</h3>
  <h3>this is the fourth paragraph</h3>
  <h4>this is the third paragraph</h4>
  <h4>this is the fourth paragraph</h4>
</body>

UI伪类选择器

使用UI伪类选择器可以根据元素的状态匹配元素。

:enabled:disabled选择器可以匹配有启用或者禁用状态的元素。

:checked选择器可以选中由checked属性或用户勾选的单选按钮或者复选框。

chap2-20.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-20</title>
    <style type="text/css">
      :enabled{border: dotted medium black;padding: 10px}
      :checked+span{background-color: rgba(0,255,0,0.4)}
    </style>
  </head>
  <body>
    <textarea>This is an enabled textarea</textarea><br>
    <textarea disabled>This is a disabled textarea</textarea><br>
    <p>
      <label for="apples">Do you like apples:</label>
      <input type="checkbox" id="apples" name="apple">
      <span>This will go green when checked</span>
    </p>
  </body>
</html>

:default选择器从一组类似的元素中选择默认元素。例如,提交按钮总是表单的默认按钮。

:valid:invalid选择器分别匹配符合和不符合它们的输入验证要求的input元素。

chap2-21.html

<head>
  <meta charset="UTF-8">
  <title>chap2-21</title>
  <style type="text/css">
    :default{outline: solid medium black}
    p>:invalid{outline: medium solid red}
    p>:valid{outline: medium dotted green}
  </style>
</head>
<body>
  <form action="chap2-2.html" method="post">
    <p>
      <label for="name">Name:</label>
      <input type="text" id="name" name="sname" pattern="[a-z]{3}">
    </p>
    <p>
      <label for="age">Age:</label>
      <input type="text" id="age" name="sage" pattern="[0-9]{2}">
    </p>
    <button type="submit">Submit</button>
    <button type="reset">Reset</button>
  </form>
</body>

:in-range选择器匹配位于指定范围内的input元素,:out-of-range选择器匹配位于指定范围之外的input元素。

:required选择器匹配具有required属性的input元素,:optional选择器匹配没有required属性的input元素。

chap2-22.html

<head><style type="text/css">
  :in-range{outline: medium dotted green}
  :out-of-range{outline: medium dotted red}
  :required{outline: solid medium orange}
  section :optional{outline: solid medium blue}
  </style></head>
<body><form action="chap2-2.html" method="post">
  <section>
    <p>
      <label for="name">Name:</label>
      <input type="text" id="name" name="sname" required>
    </p>
    <p>
      <label for="age">Age:</label>
      <input type="text" id="age" name="sage">
    </p>
  </section>
  <p>
    <label for="price">$ per unit in your area:</label>
    <input type="number" min="0" max="100" value="1" id="price" name="mprice">
  </p>
  <button type="submit">submit</button>
</form></body>

动态伪类选择器

动态伪类选择器会根据条件的改变而匹配元素。

:link选择器匹配超链接,:visited选择器匹配用户已访问的超链接。

:hover选择器匹配用户鼠标悬停在其上的任意元素。

chap2-23.html

<head>
  <meta charset="UTF-8">
  <title>chap2-23</title>
  <style type="text/css">
    :link{background-color:green;color: black;text-decoration: none}
    :visited{color: white;background-color: grey}
    a:hover{border: medium dotted red}
  </style>
</head>
<body>
  <a href="chap2-2.html">chap2-2.html</a>
  <p>I like <span>apples</span> and oranges</p>
  <a href="chap2-1.html">chap2-1.html</a>
</body>

:active选择器匹配当前被用户激活的元素。多数浏览器会在鼠标点击的情况下使用这个选择器。

:focus选择器匹配当前获得焦点的元素。

chap2-24.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-24</title>
    <style type="text/css">
      a:active{border: dotted medium red}
      :focus{border: dotted medium blue}
    </style>
  </head>
  <body>
    <p>
      <label for="name">Name:</label>
      <input type="text" id="name">
    </p>
    <a href="chap2-1.html">chap2-1.html</a>
  </body>
</html>

其他伪类选择器

:not为否定选择器,可以对任意选择取反,语法::not(选择器)

:lang选择器匹配基于lang全局属性值的元素,语法::lang(选择器)

chap2-25.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>chap2-25</title>
    <style type="text/css">
      a:not([href*="edu"]){border: dotted medium red}
      :lang(en){border: dotted medium blue}
    </style>
  </head>
  <body>
    <p></p><a lang="en" href="http://www.njfu.edu.cn">Nanjing Forestry University</a></p>
  <p><a href="http://www.jd.com">JD</a></p>
  <p><a href="http://www.nju.edu.cn">Nanjing University</a></p>
  </body>
</html>

使用边框和背景

问题 解决方案
为元素应用边框 使用border-widthborder-styleborder-color属性
为元素盒子的某一条边应用边框 使用特定边属性
在一条声明中指定边框的样式、颜色和宽度 使用border属性设置所有边的边框,或者使用border-topborder-bottomborder-leftborder-right属性设置
创建圆角边框 使用border-radius简写属性或某个特定边属性
定义背景颜色或图像 使用background-colorbackground-image属性
指定背景图像的位置 使用background-position属性
指定背景和元素滚动区域之间的关系 使用background-attachment属性
设置元素的盒子阴影 使用box-shadow属性

应用边框样式

简单边框有3个关键属性:

  • border-width属性:设置边框的宽度;
  • border-style属性:设置绘制边框使用的样式;
  • border-color属性:设置边框的颜色
border-width 说明
<长度值> CSS长度
<百分数> 边框绘制区域的宽度的百分数
thinmediumthick CSS预设宽度,依次增大
border-style 说明
none 没有边框
dashed 破折线式边框
dotted 圆点线式边框
double 双线式边框
groove 槽线式边框
inset 使元素内容具有内嵌效果的边框
outset 使元素内容具有外凸效果的边框
ridge 脊线边框
solid 实线边框

chap2-26.html

<head>
  <meta charset="UTF-8">
  <title>chap2-26</title>
  <style type="text/css">
    span{display:block;width: 200px;height: 50px;font-weight: bolder;margin: 10px}
    .class1{border-width: 5px;border-style: none;border-color: red}
    .class2{border-width: 5px;border-style: dashed;border-color: green}
    .class3{border-width: 5px;border-style: dotted;border-color: blue}
    .class4{border-width: 5px;border-style: double;border-color: blue}
    .class5{border-width: 5px;border-style: groove;border-color: orange}
    .class6{border-width: 5px;border-style: inset;border-color: red}
    .class7{border-width: 5px;border-style: outset;border-color: red}
    .class8{border-width: 5px;border-style: ridge;border-color: green}
    .class9{border-width: 5px;border-style: solid;border-color: blue}
  </style>
</head>
<body>
  <span class="class1">none</span><span class="class2">dashed</span><span class="class3">dotted</span>
  <span class="class4">double</span><span class="class5">groove</span><span class="class6">inset</span>
  <span class="class7">outset</span><span class="class8">ridge</span><span class="class9">solid</span>
</body>

元素的四条边可以应用不同的边框样式,四条边的属性如下:

属性 说明
border-top-widthborder-top-styleborder-top-color 定义顶边
border-bottom-widthborder-bottom-styleborder-bottom-color 定义底边
border-left-widthborder-left-styleborder-left-color 定义左边
border-right-widthborder-right-styleborder-right-color 定义右边

chap2-27.html

<head>
  <style type="text/css">
    p{
      width:60%;
      border-top-width: 5px;
      border-top-style: solid;
      border-top-color:black;
      border-right-width: 5px;
      border-right-style: dotted;
      border-right-color:red;
      border-bottom-width: 5px;
      border-bottom-style: inset;
      border-bottom-color:blue;
      border-left-width: 5px;
      border-left-style: double;
      border-left-color:green;
    }
  </style>
</head>
<body>
  <p>
    The fruits I like:<br>
    I like apples and oranges.<br>
    I also like mangos and cherries.
  </p>
</body>

我们也可以不用分开设置样式、宽度和颜色,而是使用简写属性一次搞定。

border属性:设置所有边的边框;

border-topborder-bottomborder-leftborder-right 属性:设置一条边的边框。

chap2-28.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>chap2-28</title>
    <style type="text/css">
      p{border: dotted medium black}
      span{
        border-top: solid 5px red;
        border-right: solid 5px blue;
        border-bottom: solid 5px green;
        border-left: solid 5px orange;
      }
    </style>
  </head>
  <body>
    <p>I like <span>apples</span> and oranges.</p>
  </body>
</html>

使用边框的radius特性可以创建圆角边框,与该功能相关的属性有5个:

属性 说明
border-top-left-radiusborder-top-right-radiusborder-bottom-left-radiusborder-bottom-right-radius 设置一个圆角 一对长度值或百分数值,百分数跟边框盒子的宽度和高度相关
border-radius 一次设置4个角的简写属性 一对长度值或百分数值,由/字符分隔

指定2个半径值即可定义一个圆角,采用长度值和百分数均可。第一个值指定水平曲线半径,第二个值指定垂直曲线半径。百分数是相对于元素盒子的宽度和高度来说的。

border-radius属性是一个简写属性,语法:border-radius: 1-4 length / 1-4 length

说明:如果/前后的值都存在,那么前面的值为水平半径,后面的值为垂直半径。如果没有/,则水平和垂直半径相等。另外,其4个值是按照top-lefttop-rightbottom-rightbottom-left的顺序来设置的。例如:

属性 说明
border-radius: <length> top-lefttop-rightbottom-rightbottom-left四个值相等
border-radius: <length1> <length2> top-left等于bottom-right,并取<length1>top-right等于bottom-left,并取<length2>
border-radius: <length1> <length2> <length3> top-left<length1>top-right等于bottom-left,并取<length2>bottom-right<length3>
border-radius: <length1> <length2> <length3> <length4> top-lefttop-rightbottom-rightbottom-left顺序取值
border-radius:2em 1em 4em / 0.5em 3em;

等价于:

border-top-left-radius: 2em 0.5em; 
border-top-right-radius: 1em 3em; 
border-bottom-right-radius: 4em 0.5em;
border-bottom-left-radius: 1em 3em; 

chap2-29.html

<head>
  <meta charset=“UTF-8”>
  <title>chap2-29</title>
  <style type=“text/css”>
  .class1{
  border: solid medium black; padding: 10px;
  border-top-left-radius:20% 15px;
  border-top-right-radius:20% 15px;
  border-bottom-left-radius:20% 15px;
  border-bottom-right-radius:20% 15px;
  }
  .class2{
  border: solid medium black; padding: 10px;
  border-radius: 2em 1em 4em / 0.5em 3em
  }
  </style>
</head>
<body>
  <p class=“class1”>Net primary production is the rate …. </p>
  <p class="class2"> Net primary production is the rate …. </p>
</body>

设置元素的背景

属性 说明
background-color 设置元素的背景颜色
background-image 设置元素的背景图像
background-repeat 设置图像的重复样式
background-size 设置背景图像的尺寸
background-position 设置背景图像的位置
background-attachment 设置元素中图像是否固定或随页面一起滚动

background-color属性设置元素的背景颜色,总是显示在背景图像下面。

background-image属性设置元素的背景图像,如果指定一个以上的图像,则后面的图像绘制在前面的图像的下面。

background-repeat属性设置图像的重复样式,其值有:

background-repeat 说明
repeat-x 水平方向平铺图像,图像可能被截断
repeat-y 垂直方向平铺图像,图像可能被截断
repeat 水平和垂直方向平铺图像,图像可能被截断
space 水平或垂直方向平铺图像,但在图像与图像之间设置统一间距,确保图像不被截断
round 水平或垂直方向平铺图像,但调整图像大小,确保图像不被截断
no-repeat 禁止平铺图像

chap2-30.html

<head><script type="text/javascript">
        function background_repeat_sel(strvalue) {            document.getElementById("DemoArea").style.backgroundRepeat=strvalue;}
        </script>
<style type="text/css">
div#DemoArea{width: 850px; height: 850px; background-color: lightgreen;
background-image: url(pic/sun.jpg);background-size: 100px 100px;
background-repeat: no-repeat;}
</style></head>
<body><div><form onsubmit="return false"><h3>background-repeat属性设置</h3>
    <input type="radio" name="repeatsel" value="repeat-x" onclick="background_repeat_sel(this.value)">repeat-x
    <input type="radio" name="repeatsel" value="repeat-y" onclick="background_repeat_sel(this.value)">repeat-y
    <input type="radio" name="repeatsel" value="repeat" onclick="background_repeat_sel(this.value)">repeat
    <input type="radio" name="repeatsel" value="space" onclick="background_repeat_sel(this.value)">space
    <input type="radio" name="repeatsel" value="round" onclick="background_repeat_sel(this.value)">round
    <input type="radio" name="repeatsel" value="no-repeat" onclick="background_repeat_sel(this.value)">no-repeat
</form></div><div id="DemoArea"></div></body>

background-size属性设置背景图像的尺寸,其值有:

background-size 说明
长度值 CSS长度值、百分数(跟图像的宽度和高度相关)
contain 等比例缩放图像,使其宽度、高度中较大者与容器横向或纵向重合,背景图像始终包含在容器内
cover 等比例缩放图像,使图像至少覆盖容器,有可能超出容器
auto 默认值,图像以本身尺寸完全显示

background-position属性设置背景图像的位置,其值有:top/bottom/left/right/center

chap2-31.html

<head>
<script type=“text/javascript”>
    function background_size_sel(strvalue) {document.getElementById("DemoSize").style.backgroundSize=strvalue;}
    </script>
<style type="text/css">
        #DemoSize{width: 850px; height: 850px; background-color: lightgreen; background-image: url(pic/sun.jpg);
            background-size: cover; background-repeat: no-repeat; background-position: center;}
            </style>
</head>
<body>
<div>
    <form onsubmit="return false">
        <h3>background-size属性</h3>
        <input type="radio" name="sizesel" value="100px 100px" onclick="background_size_sel(this.value)">100px 100px
        <input type="radio" name="sizesel" value="50% 50%" onclick="background_size_sel(this.value)">50% 50%
        <input type="radio" name="sizesel" value="contain" onclick="background_size_sel(this.value)">contain
        <input type="radio" name="sizesel" value="cover" onclick="background_size_sel(this.value)">cover
        <input type="radio" name="sizesel" value="auto" onclick="background_size_sel(this.value)">auto
    </form>
    </div>
<div id="DemoSize"></div>
</body>

background-attachment属性设置背景附着内容的方式,其值有:

background-attachment 说明
fixed 背景固定到视窗上,即内容滚动时背景不动
local 背景附着到内容上,即背景随内容一起滚动
scroll 默认值。背景固定到元素上,背景随着页面其余部分的滚动而移动。

chap2-32.html

<head>
    <meta charset="UTF-8">
    <title>chap2-32</title>
    <style type="text/css">
        body{
            background-image: url(pic/apple.jpg);
            background-repeat: no-repeat;
            background-attachment: fixed;
        }
    </style>
    </head>
<body>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
<h1>图像不会随页面的其余部分滚动</h1>
</body>

创建盒子阴影

box-shadow属性可以为元素盒子添加阴影效果。

语法:box-shadow: hoffset voffset blur spreadcolor inset

说明
hoffset 阴影的水平偏移量,是一个长度值,正值代表阴影向右偏移,负值代表阴影向左偏移
voffset 阴影的垂直偏移量,是一个长度值,正值代表阴影位于盒子下方,负值代表阴影位于盒子上方
blur (可选)指定模糊值,是一个长度值,值越大盒子的边界越模糊。默认值为0,边界清晰
spread (可选)指定阴影的延伸半径,是一个长度值,正值代表阴影向盒子各个方向延伸扩大,负值代表阴影沿相反方向缩小
color (可选)设置阴影的颜色,如果省略,浏览器会自行选择一个颜色
inset (可选)将外部阴影设置为内部阴影(内嵌到盒子中)

chap2-33.html

<head>
    <meta charset="UTF-8">
    <title>chap2-33</title>
    <style type="text/css">
        p{
            border: 10px double black;
            box-shadow: 5px 4px 10px 2px gray;
            width: 600px;
            margin:20px auto 0px auto;
        }
    </style>
    </head>
<body>
<p>In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide. </p>
</body>

我们可以在一条box-shadow声明中定义多个阴影,只需要用逗号分隔每条声明即可。

chap2-34.html

<head>
    <meta charset="UTF-8">
    <title>chap2-34</title>
    <style type="text/css">
        p{
            border: 10px double black;
            box-shadow: 5px 4px 10px 2px gray,4px 4px 6px green inset;
            width: 600px;
            margin:20px auto 0px auto;
        }
    </style>
    </head>
<body>
<p>In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide. </p>
</body>

应用轮廓

轮廓对于边框来说是可选的。轮廓最有用的地方在于短时间抓住用户对某个元素的注意力。轮廓绘制在盒子边框的外面。边框和轮廓的区别在于:轮廓不属于页面,因此应用轮廓不需要调整页面布局。

属性 说明
outline-color 设置外围轮廓的颜色 <颜色>
outline-offset 设置轮廓距离元素边框边缘的偏移量 <长度>
outline-style 设置轮廓样式 border-style属性的值一样
outline-width 设置轮廓的宽度 thinmediumthick<长度>
outline 在一条声明中设置轮廓的简写属性 <颜色> <样式> <宽度>

chap2-35.html

<head>
    <meta charset="UTF-8">
    <title>chap2-35</title>
    <style type="text/css">
        p{
            width: 30%;
            padding: 5px;
            border: medium double black;
            background-color: lightgray;
            margin: 2px;
            float: left;
        }
        #fruittext{outline: thin solid red}
    </style>
    </head>
<body>
<p>It principally occurs through the process of photosynthesis,</p>
<p id="fruittext">It principally occurs through the process of photosynthesis, </p>
<p>It principally occurs through the process of photosynthesis, </p>
</body>

盒模型属性

问题 解决方案
设置盒子内边距区域的尺寸 使用padding简写元素,或padding-toppadding-bottompadding-leftpadding-right属性
设置盒子外边距区域的尺寸 使用margin简写元素,或margin-topmargin-bottommargin-leftmargin-right属性
设置元素的尺寸 使用widthheight属性
设置尺寸应用到盒子的哪一部分 使用box-sizing属性
为元素大小设置范围 使用max-widthmin-widthmax-heightmin-height属性
设置元素溢出内容的处理方式 使用overflowoverflow-xoverflow-y属性
设置元素的可见性 使用visibility属性或display:none
设置元素盒子的类型 使用display属性
将元素移动到其包含块的左边界或右边界,或者另一个浮动元素的边界 使用float属性
设置盒子的左边界、右边界或左右两个边界不允许出现浮动元素 使用clear属性

为元素应用内边距

使用padding简写元素,或padding-toppadding-bottompadding-leftpadding-right属性。当使用padding简写元素时:

属性值 说明
padding:<length1> <length2> <length3> <length4> 按上、右、下、左的顺序取值
padding:<length1> <length2> <length3> 上:length1;右和左:length2;下:length3
padding:<length1> <length2> 上和下:length1;右和左:length2
padding:<length1> 所有4个内边距都是length1

chap2-36.html

<head><style type="text/css">
        p{
            border: medium dotted black;
            width: 40%;
        }
        span{border: solid thin red}
        </style></head>
<body>
<p>
    <form onsubmit="return false">
        <span><input type="radio" name="paddingsel" value="30px 50px 30px 50px" onclick="mysel(this.value)">30px 50px 30px 50px</span>
    <span><input type="radio" name="paddingsel" value="5px 25px 5px" onclick="mysel(this.value)">5px 25px 5px</span>
    <span><input type="radio" name="paddingsel" value="30px 50px" onclick="mysel(this.value)">30px 50px</span>
    <span><input type="radio" name="paddingsel" value="25px" onclick="mysel(this.value)">25px</span>
    </form>
    </p>
<p id="DemoArea">It principally occurs through the process of photosynthesis, </p>
<script type="text/javascript">
    function  mysel(strvalue) {
        document.getElementById("DemoArea").style.padding=strvalue;
    }
    </script>
</body>

为元素应用外边距

使用margin简写元素,或margin-topmargin-bottommargin-leftmargin-right属性。当使用margin简写元素时,其用法与padding相似。

chap2-37.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-37</title>
    <style type="text/css">
        img{
            border:thin solid black;
            background-color: lightgray;
            padding: 4px;
            margin: 10px 20px;
            width: 40%;
            height: 40%;
        }
    </style>
    </head>
<body>
<img src="pic/venus.jpg">
<img src="pic/sun.jpg">
</body>
</html>

控制元素的尺寸

widthheight属性用于设置元素的宽度和高度。

max-widthmin-widthmax-heightmin-height属性用于设置元素可接受的宽度和高度范围。

box-sizing属性设置尺寸调整应用到元素盒子的哪一部分。

box-sizing 说明
content-box 宽度和高度分别应用到元素的内容框。在宽度和高度之外绘制元素的内边距和边框。
border-box 为元素设定的宽度和高度决定了元素的边框盒。就是说,为元素指定的任何内边距和边框都将在已设定的宽度和高度内进行绘制。通过从已设定的宽度和高度分别减去边框和内边距才能得到内容的宽度和高度。

chap2-38.html

<head><style type="text/css">
        div{
            width: 75%;
            height: 800px;
            border: solid thin black;
        }
        img{
            background-color: lightgray;
            border: medium double orangered;
            margin: 2px;
            height: 400px;
        }
        #first{box-sizing: border-box;}
        #second{box-sizing:content-box;}
        #third{max-width: 300px;max-height: 300px}
    </style>
    </head>
<body>
<div>
    <img id="first" src="pic/sun.jpg">
    <img id="second" src="pic/sun.jpg">
    <img id="third" src="pic/sun.jpg">
    </div>
</body>

处理溢出内容

使用overflowoverflow-xoverflow-y属性可以设置溢出内容的处理方式,这3个属性可能的取值有:

说明
auto 浏览器自行处理溢出内容。通常,如果内容被剪掉就显示滚动条,否则就不显示
hidden 多余的部分直接剪掉,只显示内容盒里面的内容
scroll 为了让用户看到所有内容,浏览器会添加滚动机制,通常是滚动条。即使内容没有溢出也能看到滚动条
visible 默认值,不管是否溢出内容盒,都显示元素内容

chap2-39.html

<head><style type=“text/css”>
        p{
            width: 300px;
            height: 200px;
            border: medium dotted black;
            float: left;
        }
        #first{overflow: hidden}
        #second{overflow: scroll}
        #third{overflow: auto}
        #fourth{overflow: visible}
    </style></head>
    <body>
<p id=“first”>In ecology, …</p>
<p id="second">In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide. </p>
<p id="third">In ecology, … </p>
<p id="fourth">In ecology, … </p>
</body>

控制元素的可见性

使用visibility属性可以控制元素的可见性,可能的取值有:

visibility属性值 说明
collapse 元素不可见,且在页面布局中不占据空间。
hidden 元素不可见,但在页面布局中占据空间
visible 默认值,元素在页面上可见

chap2-40.html

<head><style type="text/css">
        tr>th{text-align: left;background-color: gray;color: white}
        tr>th:only-of-type{text-align: right;background-color: lightgray;color: gray}
        </style></head>
<body>
<table>
    <tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th></tr>
    <tr id="firstchoice"><th>Favorite:</th><td>Apples</td><td>Green</td><td>Medium</td></tr>
    <tr><th>2nd Favorite:</th><td>Oranges</td><td>Orange</td><td>Large</td></tr>
    </table>
<p><button>Visible</button><button>Collapse</button><button>Hidden</button></p>
<script>
    var buttons=document.getElementsByTagName("button");
    for(var i=0;i<buttons.length;i++){
        buttons[i].onclick=function (e) {
            document.getElementById("firstchoice").style.visibility=e.target.innerHTML;
        }
    }
    </script>
</body>

设置元素的盒类型

使用display属性可以改变元素的盒类型:

display属性值 说明
inline 盒子显示为文本行中的字
block 盒子显示为段落
inline-block 盒子显示为文本行
list-item 盒子显示为列表项,通常具有项目符号或者其他标记符(如索引号)
run-in 盒子类型取决于周围的元素
flexbox 这个值跟弹性盒布局相关
table 这些值跟表格中的元素布局相关
none 元素不可见,且在页面布局中不占空间

display属性设置为block值会创建一个块级元素。块级元素会在垂直方向跟周围元素有所区别。通常在元素前后放置换行符也能达到这种效果。

block值可应用到所有元素。

chap2-41.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-41</title>
    <style type="text/css">
        p{border: medium dotted black}
        span{display: block;border: medium double red;margin: 2px}
    </style>
    </head>
<body>
<p>In ecology, …</p>
<p>In ecology, … <span>It principally occurs through the process of photosynthesis, … </span> Almost all life on Earth relies directly or indirectly on primary production.</p>
</body>
</html>

inline值会创建一个行内元素。

inline-block值会创建一个其盒子混合了块和行内特征的元素,盒子整体作为行内元素显示。但盒子内部作为块元素显示,这样,widthheightmargin属性都能应用到盒子上。

chap2-42.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-42</title>
    <style type="text/css">
        p{display: inline}
        span#s1{display: inline;border: medium double red;width: 12em;height: 2em}
        span#s2{display: inline-block; border: medium double red;width: 12em;height: 2em}
    </style>
    </head>
<body>
<p>In ecology, primary production is the <span id="s1">synthesis of organic</span> compounds from atmospheric or aqueous carbon dioxide. </p>
<p>In ecology, primary production is the <span id="s2">synthesis of organic</span> compounds from atmospheric or aqueous carbon dioxide. </p>
</body>
</html>

run-in值会创建一个这样的元素:其盒子类型取决于周围元素。通常,浏览器(Chrome不支持,IE支持)必须评估以下2种情况,以确定插入框的特征:

  • 如果插入元素的相邻兄弟元素是块级元素,那么插入元素就是兄弟元素中的第一个行内元素。
  • 其他情况下,插入元素均作为块级元素对待。

chap2-43.html

<head>
    <meta charset="UTF-8">
    <title>chap2-43</title>
    <style type="text/css">
        p#p1{display: block}
        p#p2{display: inline}
        span{display: run-in;border: medium double red}
    </style>
    </head>
<body>
<h1>display:block</h1>
<span>In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide.</span>
<p id="p1">It principally occurs through the process of photosynthesis , … </p>
<h1>display:inline</h1>
<span>In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide.</span>
<p id="p2">It principally occurs through the process of photosynthesis, … </p>
</body>

none值就是告诉浏览器不要为元素创建任何类型的盒子,这时元素在页面布局中不占据任何空间。

chap2-44.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-44</title>
    <style type="text/css">
        #p1{display: none}
        #p2{display: block}
    </style>
    </head>
<body>
<h1>display:none</h1>
<p id="p1">In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide. </p>
<h1>display:block</h1>
<p id="p2">In ecology, primary production is the synthesis of organic compounds from atmospheric or aqueous carbon dioxide. </p>
</body>
</html>

创建浮动盒

可以使用float属性创建浮动盒,浮动盒会将元素的左边界或者右边界移动到包含块或另一个浮动盒的边界。其值有以下3个:

float属性值 说明
left 移动元素,使其左边界挨着包含块的左边界,或者另一个浮动元素的右边界
right 移动元素,使其右边界挨着包含块的右边界,或者另一个浮动元素的左边界
none 元素位置固定

clear属性规定元素的哪一侧不允许其他浮动元素。其值有以下4个:

clear属性值 说明
left 元素的左边界不能挨着另一个浮动元素
right 元素的右边界不能挨着另一个浮动元素
both 元素的左右边界都不能挨着浮动元素
none 元素的左右边界都可以挨着浮动元素

chap2-45.html

<head>
    <style type="text/css">
        p.toggle{float: left; border: medium double red; width: 40%; margin: 2px; padding: 2px}
    p.cleared{clear: left}
    </style>
</head>
<body>
    <p class="toggle">Gross primary production (GPP) …</p>
    <p class="toggle cleared">Net primary production …</p>
    <p>In areal terms, …</p>
    <p><button>Left</button><button>Right</button><button>None</button></p>
    <script type="text/javascript">
        var buttons=document.getElementsByTagName("button");
        for(var i=0;i<buttons.length;i++){
            buttons[i].onclick=function (e) {
                var elem=document.getElementsByClassName("toggle");
                for(var j=0;j<elem.length;j++){
                    elem[j].style.float=e.target.innerHTML;
                }
            }
        }
    </script>
</body>

布局属性

问题 解决方案
改变元素在容器块中的定位方式 使用position属性
设置定位元素相对于容器边界的偏移量 使用topbottomleftright属性
设置元素的层叠顺序 使用z-index属性
创建跟报纸页面类似的布局 使用多列布局
将空间流式分配到容器中的元素 使用弹性盒布局
为元素创建表格样式布局 使用CSS表布局

定位内容

position属性设置了元素的定位方法。

使用topbottomleftright属性设置元素的偏移量的时候,指的是相对于position属性指定的元素的偏移量。

position属性值 说明
static 默认值。没有定位,元素出现在正常的流中(忽略top, bottom, left, right或者 z-index声明)。
relative 生成相对定位的元素,相对于其正常位置进行定位。因此,left:20会向元素的LEFT位置添加20像素。
absolute 生成绝对定位的元素,相对于static定位以外的第一个父元素进行定位。元素的位置通过 left, top, right以及bottom属性进行规定。
fixed 生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过left,top,right以及bottom属性进行规定。

chap2-46.html

<head>
    <meta charset="UTF-8">
    <title>chap2-46</title>
    <style type="text/css">
        p{width:500px;position: relative;left: 150px}
        img{top: 200px;left: 150px; position:absolute;border: medium double black;width: 300px}
    </style>
    </head>
<body>
<p>In ecology, ….</p>
<img src="pic/apple.jpg" id="apple">
<p><button>Static</button><button>Relative</button><button>Absolute</button><button>Fixed</button></p>
<script type="text/javascript">
    var buttons=document.getElementsByTagName("button");
    for(var i=0;i<buttons.length;i++){
        buttons[i].onclick=function (e) {
            document.getElementById("apple").style.position=e.target.innerHTML;
        }
    }
    </script>
</body>

z-index属性指定元素显示的层叠顺序,其值为数值,且允许取负值。值越小,在层叠顺序中就越靠后。这个属性只有在元素重叠的情况下才会排上用场。

z-index属性默认值是0。因此,浏览器默认将图像显示在p元素上面。

chap2-47.html

<!DOCTYPE html>
<html lang=“en”>
<head>
    <meta charset=“UTF-8”>
    <title>chap2-47</title>
    <style type=“text/css”>
        img{border: medium double black;position: fixed;width: 300px}
        #sun{z-index: 1;top: 15px;left: 250px}
        #venus{z-index: 2;top: 25px;left: 120px}
    </style>
    </head>
<body>
<p>The Sun is the star at the center of the Solar System. …</p>
<p>Venus is the second planet from the Sun, orbiting it every 224.7 Earth days….</p>
<img id="sun" src="pic/sun.jpg"><img id="venus" src="pic/venus.jpg">
</body>
</html>

创建多列布局

多列特性允许在多个垂直列中布局内容,跟报纸的排版方式类似。

属性 说明
column-count 指定列数
column-gap 指定列之间的距离
column-rule 设置列之间的颜色、样式、宽度

column-gap属性规定列之间的间隔。语法为:column-gap:长度|normal

column-rule属性是一个简写属性,用于设置所有column-rule-*属性。语法:column-rule: column-rule-width column-rule-style column-rule-color

chap2-48.html

<head><style type=“text/css”>
        div.SelArea{border: medium dotted black;float: left;margin: 5px}
        div.ResultArea{width: 80%;column-count: 3;column-gap: 5px;column-rule: 4px double red}
        </style></head>
<body>
<div class=“SelArea”>
    <form onsubmit=“return false”>
        <ul>
            <li><input type=“radio” name=“rpos” value=“5px” onclick=“columngap(this.value)”>5px</li>
            <li><input type=“radio” name=“rpos” value=“10px” onclick=“columngap(this.value)”>10px</li>
            <li><input type=“radio” name=“rpos” value=“20px” onclick=“columngap(this.value)”>20px</li>
            <li><input type=“radio” name=“rpos” value=“normal” onclick=“columngap(this.value)”>normal</li>
        </ul>
    </form>
    </div>
<div class=“SelArea ResultArea” id=“DemoArea”>人民网北京…</div>
<script type="text/javascript">
    function columngap(strValue) {
        document.getElementById("DemoArea").style.columnGap=strValue;
    }
</script></body>

创建弹性盒布局

弹性盒(flexbox)布局主要思想是让容器有能力让其子项目能够改变其宽度、高度(甚至顺序),以最佳方式填充可用空间(主要是为了适应所有类型的显示设备和屏幕大小)。Flex容器会使子项目(伸缩项目)扩展来填满可用空间,或缩小他们以防止溢出容器。

任何一个容器都可以指定为Flex布局,例如:.box{display:flex;}

行内元素也可以使用Flex布局,例如:.box{display:inline-flex;}

Webkit 内核的浏览器,必须加上-webkit前缀。例如:.box{display: -webkit-flex;}

注意:设为 Flex 布局以后,子元素的floatclearvertical-align属性将失效。

采用 Flex 布局的元素,称为 Flex 容器(flex container),简称"容器"。它的所有子元素自动成为容器成员,称为 Flex 项目(flex item),简称“项目”。

容器默认存在两根轴:水平的主轴(main axis)和垂直的交叉轴(cross axis)。主轴的开始位置(与边框的交叉点)叫做main start,结束位置叫做main end;交叉轴的开始位置叫做cross start,结束位置叫做cross end

项目默认沿主轴排列。单个项目占据的主轴空间叫做main size,占据的交叉轴空间叫做cross size

2.5.3 创建弹性盒布局

容器的属性有:

属性 说明
flex-direction 决定主轴的方向
flex-wrap 默认情况下,项目都排在一条线(又称“轴线”)上。flex-wrap属性定义,如果一条轴线排不下,如何换行
flex-flow flex-direction属性和flex-wrap属性的简写形式,默认值为row nowrap
justify-content 定义了项目在主轴上的对齐方式
align-items 定义项目在交叉轴上如何对齐
align-content 定义了多根轴线的对齐方式。如果项目只有一根轴线,该属性不起作用

项目的属性有:

属性 说明
order 定义项目的排列顺序。数值越小,排列越靠前,默认为0。
flex-grow 定义项目的放大比例,默认为0,即如果存在剩余空间,也不放大。
flex-shrink 定义了项目的缩小比例,默认为1,即如果空间不足,该项目将缩小。
flex-basis 定义了在分配多余空间之前,项目占据的主轴空间(main size)。浏览器根据这个属性,计算主轴是否有多余空间。它的默认值为auto,即项目的本来大小。
flex flex-grow, flex-shrinkflex-basis的简写,默认值为0 1 auto。后两个属性可选。
align-self 允许单个项目有与其他项目不一样的对齐方式,可覆盖align-items属性。默认值为auto,表示继承父元素的align-items属性,如果没有父元素,则等同于stretch

容器属性

flex-direction属性决定主轴的方向(即项目的排列方向)。

语法:flex-direction: row | row-reverse |column | column-reverse

默认情况下,项目都排在一条线(又称"轴线")上。

flex-wrap属性定义,如果一条轴线排不下,如何换行。语法:flex-wrap:nowrap | wrap | wrap-reverse

  • nowrap(默认):不换行。

  • wrap:换行,第一行在上方。

  • wrap-reverse:换行,第一行在下方。

justify-content属性定义了项目在主轴上的对齐方式。

语法:justify-content: flex-start | flex-end |center | space-between | space-around

  • space-around:弹性盒子元素会平均地分布在行里,两端保留子元素与子元素之间间距大小的一半。如果最左边的剩余空间是负数,或该行只有一个伸缩盒项目,则该值等效于center。在其它情况下,伸缩盒项目则平均分布,并确保两两之间的空白空间相等,同时第一个元素前的空间以及最后一个元素后的空间为其他空白空间的一半。

align-items属性定义项目在交叉轴上如何对齐。

语法:align-items: flex-start | flex-end |center | baseline | stretch

  • stretch是默认值。
  • baseline:项目的第一行文字的基线对齐。

align-content属性定义了多根轴线的对齐方式。如果项目只有一根轴线,该属性不起作用。

align-content属性定义了多根轴线的对齐方式。如果项目只有一根轴线,该属性不起作用。

语法:align-content: flex-start | flex-end |center | space-between | space-around | stretch

chap2-49.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-49</title>
    <style type="text/css">
        p{float: left;width: 150px;border: medium double black;background-color: lightgray;margin: 2px}
        #container{display: flex;flex-direction: row-reverse;justify-content: space-between;align-items: flex-end}
    </style>
    </head>
<body>
<div id="container">
    <p id="first">In ecology, primary production is … </p>
    <p id="second">Gross primary production (GPP) is …</p>
    <p id="third">Net primary production is …</p>
    </div>
</body>
</html>

项目属性

order属性定义项目的排列顺序。数值越小,排列越靠前,默认为0。

  • 语法:order: <integer>

flex-grow属性定义项目的放大比例,默认为0,即如果存在剩余空间,也不放大。

  • 语法:flex-grow: <number>
  • 如果所有项目的flex-grow属性都为1,则它们将等分剩余空间(如果有的话)。如果一个项目的flex-grow属性为2,其他项目都为1,则前者占据的剩余空间将比其他项多一倍。

flex-shrink属性定义了项目的缩小比例,默认为1,即如果空间不足,该项目将缩小。

  • 语法:flex-shrink: <number>
  • 如果所有项目的flex-shrink属性都为1,当空间不足时,都将等比例缩小。如果一个项目的flex-shrink属性为0,其他项目都为1,则空间不足时,前者不缩小。负值对该属性无效。

flex-basis属性定义了在分配多余空间之前,项目占据的主轴空间(main size)。浏览器根据这个属性,计算主轴是否有多余空间。它的默认值为auto,即项目的本来大小。

  • 语法:flex-basis: <length> | auto

flex属性是flex-growflex-shrinkflex-basis的简写,默认值为0 1 auto。后两个属性可选。

  • 该属性有两个快捷值:auto (1 1 auto) 和 none (0 0 auto)。

align-self属性允许单个项目有与其他项目不一样的对齐方式,可覆盖align-items属性。默认值为auto,表示继承父元素的align-items属性,如果没有父元素,则等同于stretch

语法:align-self: auto | flex-start | flex-end | center | baseline | stretch

cahp2-50.html

<head>
<style type="text/css">
        .HolyGrail{display: flex;flex-direction: column}
        header,footer{flex: 1;background-color: gray}
        .HolyGrail-body{display: flex;flex: 1}
        .HolyGrail-content{flex: 1;background-color: lightblue}
        .HolyGrail-nav,.HolyGrail-ads{flex: 0 0 250px;background-color: lightgreen}
        .HolyGrail-nav{order: -1;background-color: lightpink}
    </style>
    </head>
<body class="HolyGrail">
<header>
    <h1>This is the header</h1>
    </header>
<div class="HolyGrail-body">
    <div class="HolyGrail-content"><h2>HolyGrail-content</h2></div>
    <div class="HolyGrail-nav"><h2>HolyGrail-nav</h2></div>
    <div class="HolyGrail-ads"><h2>HolyGrail-ads</h2></div>
    </div>
<footer>
    <h1>This is the footer</h1>
    </footer>
</body>

创建表格布局

创建CSS表格布局使用display属性,其值有:

display属性值 说明
table 类似于table元素
inline-table 类似于table元素,但是创建一个行内元素
table-caption 类似于caption元素
table-column 类似于col元素
table-column-group 类似于colgroup元素
table-header-group 类似于thead元素
table-row-group 类似于tbody元素
table-footer-group 类似于tfoot元素
table-row 类似于tr元素
table-cell 类似于td元素

chap2-51.html

<head><style type="text/css">
        #table{display: table}
        #thead{display: table-header-group;background-color: gray; font-weight: bold}
        #tbody{display: table-row-group}
        #tbody p:nth-child(even){background-color: lightgreen}
        .row{display: table-row;text-align: center}
        .col{display: table-cell;border: solid thin black} </style></head>
<body>
  <div id="table">
    <div id="thead">
      <p class="row">
        <span class="col">Rank</span><span class="col">Name</span>
        <span class="col">Color</span><span class="col">Size</span>
      </p>
    </div>
    <div id="tbody">
      <p class="row">
        <span class="col">Favorite:</span><span class="col">Apples</span>
        <span class="col">Green</span><span class="col">Medium</span>
      </p>
      <p class="row">
        <span class="col">2nd Favorite:</span><span class="col">Oranges</span>
        <span class="col">Orange</span><span class="col">Large</span>
      </p>
    </div>
  </div>
</body>

文本属性

问题 解决方案
文本块对齐 使用text-aligntext-justify属性
定义如何处理空白 使用white-space属性
指定文本方向 使用direction属性
指定单词之间、字母之间、文本行之间的间隔 使用letter-spacingword-spacingline-height属性
指定溢出文本如何断行 使用word-wrap属性
指定文本缩进 使用text-indent属性
装饰文本或转换文本大小写 使用text-decorationtext-transform属性
为文本块应用阴影效果 使用text-shadow属性
设置字体 使用fontfont-familyfont-sizefont-stylefont-variantfont-weight属性

应用基本文本样式

text-aligntext-justify属性指定文本块的对齐方式,其值有:

  • start:内容对齐开始边界;
  • end:内容对齐结束边界;
  • left:内容左对齐;
  • center:内容居中对齐;
  • right:内容右对齐;
  • justify:内容两端对齐。

注意:text-justify只有IE支持!

如果使用justify值,可以使用text-justify属性指定文本添加空白的方式,其值有:

text-justify属性值 说明
auto 浏览器选择对齐规则
none 禁用文本对齐
inter-word 空白分布在单词之间,适用于英语等词间有空的语言
inter-ideograph 空白分布在单词、表意字之间,且文本两端对齐,适用于汉语、日文或韩文等语言
inter-cluster 空白分布在单词、字形集的边界,适用于泰文等无词间空格的语言
distribute 空白分布在单词、字形集的边界,但连续文本或者草体除外
kashida 通过拉长选定字符调整对齐方式(仅适用于草体)

chap2-52.html

<head><style type="text/css">
    #NPPtext{width: 400px; margin: 5px;padding: 5px;border: medium double black;background-color: lightgray}
    </style>
</head>
<body>
    <p id="NPPtext">Net primary production is the rate …</p>
    <p><button>Start</button><button>End</button><button>Left</button><button>Right</button><button>Center</button>
        <span>Justify:<select id="Justify_sel"><option value="auto">auto</option><option value="none">none</option>
        <option value="inter-word">inter-word</option><option value="inter-ideograph">inter-ideograph</option>
        <option value="inter-cluster">inter-cluster</option><option value="distribute">distribute</option>
        <option value="kashida">kashida</option></select></span>
    </p>
    <script type="text/javascript">
    var buttons=document.getElementsByTagName("button");
    for(var i=0;i<buttons.length;i++){
    buttons[i].onclick=function (e) {
    document.getElementById("NPPtext").style.textAlign=e.target.innerHTML;
    }
    }
    document.getElementById("Justify_sel").onchange=function (e) {
    document.getElementById("NPPtext").style.textAlign="Justify";
    document.getElementById("NPPtext").style.textJustify=e.target.value;
    }
    </script>
</body>

white-space属性指定空白字符的处理方式,其值有:

white-space属性值 说明
normal 默认。空白会被浏览器忽略。
pre 空白会被浏览器保留。其行为方式类似HTML中的<pre>标签。
nowrap 文本不会换行,文本会在同一行上继续,直到遇到<br>标签为止。
pre-wrap 保留空白符序列,但是正常地进行换行。
pre-line 合并空白符序列,但是保留换行符。
inherit 规定应该从父元素继承white-space属性的值。

chap2-53.html

<head>
<style type="text/css">p{white-space: normal;font-size: larger;border: double medium black;width: 600px}</style>
</head>
<body><p id="p1">
    This is the paragraph.
    This is the paragraph.
    This is the paragraph.
    This is the paragraph.
    This is the paragraph.
    This is the paragraph.
    This is the paragraph.
    This is the paragraph.
    </p>
<select onchange="whitespace(this)" size="5">
    <option selected/>normal    <option />pre    <option />nowrap    <option />pre-wrap    <option />pre-line
    </select>
<script>
    function whitespace(x) {
        var ws=x.options[x.selectedIndex].text;
        document.getElementById("p1").style.whiteSpace=ws;
    }
    </script>
</body>

direction属性告诉浏览器文本块的排列方向,其值有:

  • ltr:默认。文本方向从左到右。
  • rtl:文本方向从右到左。

letter-spacing属性设置字母间的间距,语法:letter-spacing: normal | <长度值>

word-spacing属性设置单词间的间距,语法:word-spacing: normal | <长度值>

line-height属性设置行高,语法:line-height: normal | <长度值>

chap2-54.html

<head>
    <meta charset="UTF-8">
    <title>chap2-54</title>
    <style type="text/css">
        p{border: double medium black;margin: 10px;padding: 10px}
        #GPP{direction: ltr;word-spacing: 5px;letter-spacing: 2px;line-height: 2em}
        #NPP{direction: rtl;word-spacing: 10px;letter-spacing: normal;line-height: 4em}
    </style>
</head>
<body>
    <p id="GPP">Gross primary production (GPP) is the amount of chemical energy as biomass that primary producers create in a given length of time.</p>
    <p id="NPP">Net primary production is the rate at which all the plants in an ecosystem produce net useful chemical energy; it is equal to the difference between the rate at which the plants in an ecosystem produce useful chemical energy (GPP) and the rate at which they use some of that energy during respiration.</p>
</body>

word-wrap属性告诉浏览器当一个单词的长度超出包含块的宽度时如何处理,其值有:

  • normal:单词不断开,即使无法完全放入包含块元素。
  • break-word:断开单词,使其放入包含块元素。

text-indent属性用于指定文本块首行缩进,其值可以是长度值,也可以是相对于元素宽度的百分数值。

chap2-55.html

<head>
    <meta charset="UTF-8">
    <title>chap2-55</title>
    <style type="text/css">
        p{width: 250px;margin: 20px;padding: 5px;border: medium solid black;float: left}
        #NPP1{word-wrap: break-word;text-indent: 2em}
        #NPP2{word-wrap: normal;text-indent: 10%}
    </style>
</head>
<body>
    <p id="NPP1">Net primary production is the rate at which all the plants in an ecosystemproducenetusefulchemicalenergy; it is equal to the difference between the rate at which the plants in an ecosystem produce useful chemical energy (GPP) and the rate at which they use some of that energy during respiration.</p>
    <p id="NPP2">Net primary production is the rate at which all the plants in an ecosystemproducenetusefulchemicalenergy; it is equal to the difference between the rate at which the plants in an ecosystem produce useful chemical energy (GPP) and the rate at which they use some of that energy during respiration.</p>
</body>

文本装饰与大小写转换

text-decoration属性规定添加到文本的修饰,其值有:

  • none:默认,定义标准的文本。
  • underline:定义文本下的一条线。
  • overline:定义文本上的一条线。
  • line-through:定义穿过文本下的一条线。
  • inherit:规定应该从父元素继承text-decoration属性的值。

text-transform属性控制文本的大小写,其值有:

  • none:默认。定义带有小写字母和大写字母的标准的文本。
  • capitalize:文本中的每个单词以大写字母开头。
  • uppercase:定义仅有大写字母。
  • lowercase:定义无大写字母,仅有小写字母。
  • inherit:规定应该从父元素继承text-transform属性的值。

chap2-56.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-56</title>
    <style type="text/css">
        p{line-height: 4em;font-size: larger}
        .c1{text-decoration: none;text-transform: none}
        .c2{text-decoration: underline;text-transform: capitalize}
        .c3{text-decoration: overline;text-transform: uppercase}
        .c4{text-decoration: line-through;text-transform: lowercase}
    </style>
    </head>
<body>
<p class="c1">This is some text in a paragraph.</p>
<p class="c2">This is some text in a paragraph.</p>
<p class="c3">This is some text in a paragraph.</p>
<p class="c4">This is some text in a paragraph.</p>
</body>
</html>

创建文本阴影

text-shadow属性为文本创建阴影效果。

语法: text-shadow: h-shadow v-shadowblur color

  • h-shadow:必需。水平阴影的位置。允许负值。
  • v-shadow:必需。垂直阴影的位置。允许负值。
  • blur:可选。模糊的距离。
  • color:可选。阴影的颜色。

chap2-57.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-57</title>
    <style type="text/css">
        .c1{text-shadow: 0 0 8px #ff0000}
        .c2{text-shadow: 2px 2px 8px #000000;color: white}
        .c3{text-shadow: 2px 2px 8px #ff0000}
    </style>
    </head>
<body>
<h1 class="c1">霓虹灯效果的文本阴影!</h1>
<h1 class="c2">白色文本的阴影效果!</h1>
<h1 class="c3">模糊效果的文本阴影!</h1>
</body>
</html>

使用字体

属性 说明
font-family 指定文本块采用的字体名称
font-size 指定文本块的字体大小
font-style 指定字体样式
font-variant 指定字体是否以小型大写字母显示
font-weight 设置字体粗细
font 在一条声明中设置字体的简写属性

font-family属性指定使用的字体,按照优先顺序排列。CSS定义了5种通用字体系列:

  • serif:这些字体成比例,而且有上下短线。如果字体中的所有字符根据其不同大小有不同的宽度,则该字符是成比例的。例如,小写 i 和小写 m 的宽度就不同。上下短线是每个字符笔划末端的装饰,比如小写 l 顶部和底部的短线,或大写 A 两条腿底部的短线。Serif 字体的例子包括 Times、Georgia 和 New Century Schoolbook。

  • sans-serif:这些字体是成比例的,而且没有上下短线。Sans-serif 字体的例子包括 Helvetica、Geneva、Verdana、Arial 或 Univers。

  • monospace:Monospace 字体并不是成比例的。它们通常用于模拟打字机打出的文本、老式点阵打印机的输出,甚至更老式的视频显示终端。采用这些字体,每个字符的宽度都必须完全相同,所以小写的i 和小写的 m 有相同的宽度。这些字体可能有上下短线,也可能没有。如果一个字体的字符宽度完全相同,则归类为Monospace 字体,而不论是否有上下短线。Monospace 字体的例子包括 Courier、Courier New 和 Andale Mono。

  • cursive:这些字体试图模仿人的手写体。通常,它们主要由曲线和 Serif 字体中没有的笔划装饰组成。例如,大写 A 再其左腿底部可能有一个小弯,或者完全由花体部分和小的弯曲部分组成。Cursive 字体的例子包括 Zapf Chancery、Author 和 Comic Sans。

  • fantasy:这些字体无法用任何特征来定义,只有一点是确定的,那就是我们无法很容易地将其规划到任何一种其他的字体系列当中。这样的字体包括Western、Woodblock 和 Klingon。

chap2-58.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap2-58</title>
    <style type="text/css">
        .serif{font-family:"Times New Roman",Georgia,Serif}
        .sansserif{font-family:Arial,Verdana,Sans-serif}
        .monospace{font-family: "Courier New","Andale Mono",monospace}
        .cursive{font-family: "Zapf Chancery","Comic Sans MS",Cursive}
        .fantasy{font-family: Western,Woodblock,fantasy}
    </style>
    </head>
<body>
<p class="serif">This is a paragraph, shown in the Times New Roman font.</p>
<p class="sansserif">This is a paragraph, shown in the Arial font.</p>
<p class="monospace">This is a paragraph, shown in the Courier font.</p>
<p class="cursive">This is a paragraph, shown in the Aapf Chancery font.</p>
<p class="fantasy">This is a paragraph, shown in the Western font.</p>
</body>
</html>

font-size属性用来指定字体大小,其值有:

  • 由小到大排列:xx-smallx-smallsmallmediumlargex-largexx-large。具体大小由浏览器决定。
  • smallerlarger设置字体相对于父元素字体的大小。
  • <length>使用CSS长度值精确设置字体大小。
  • <%>将字体大小表示为父元素字体大小的百分数。

font-weight属性用来指定字体粗细程度,其值有:

  • 由细到粗排列:lighternormalboldbolder
  • 数值:100200300400500600700800900400等同于normal700等同于bold

font-style属性用来指定字体风格,其值有:

  • normal:默认值。浏览器显示一个标准的字体样式。

  • italic:浏览器会显示一个斜体的字体样式。

  • oblique:浏览器会显示一个倾斜的字体样式。

  • inherit:规定应该从父元素继承字体样式。

font-variant属性用来设置小型大写字母的字体显示文本,这意味着所有的小写字母均会被转换为大写,但是所有使用小型大写字体的字母与其余文本相比,其字体尺寸更小。其值有:

  • normal:默认值。浏览器会显示一个标准的字体。

  • small-caps:浏览器会显示小型大写字母的字体。

  • inherit:规定应该从父元素继承 font-variant 属性的值。

chap2-59.html

<head>
    <meta charset="UTF-8">
    <title>chap2-59</title>
    <style type="text/css">
        .c1{font-size: xx-large;font-weight:lighter;font-style: italic;font-variant: normal}
        .c2{font-size: x-large;font-weight:normal;font-style: normal;font-variant: small-caps}
        .c3{font-size: large;font-weight:400;font-style: normal;font-variant: small-caps}
        .c4{font-size: medium;font-weight:bold;font-style: oblique;font-variant: normal}
        .c5{font-size: small;font-weight:700;font-style: oblique;font-variant: normal}
        .c6{font-size: x-small;font-weight:bolder;font-style: normal;font-variant: normal}
        .c7{font-size: xx-small;font-weight:900;font-style: normal;font-variant: normal}
    </style>
    </head>
<body>
<p class="c1">This is a Paragraph</p>
<p class="c2">This is a Paragraph</p>
<p class="c3">This is a Paragraph</p>
<p class="c4">This is a Paragraph</p>
<p class="c5">This is a Paragraph</p>
<p class="c6">This is a Paragraph</p>
<p class="c7">This is a Paragraph</p>
</body>

其他属性

问题 解决方案
设置元素的前景色 使用color属性
设置元素的透明度 使用opacity属性
指定如何绘制相邻表格单元的边框 使用border-collapseborder-spacing属性
指定表格标题的位置 使用caption-side属性
指定如何确定表格尺寸 使用table-layout属性
指定列表标记的类型 使用list-style-type属性
将图像作为列表标记 使用list-style-image属性
指定列表标记的位置 使用list-style-position属性
指定光标的形状 使用cursor属性

设置元素的颜色和透明度

color属性用来设置元素的前景色。

opacity属性设置元素的不透明级别,从0.0(完全透明)到1.0(完全不透明)。

chap2-60.html

<head>
<style type="text/css">
h1:hover{color: red} </style>
</head>
<body>
<h1 id="p1">请从下面的例子中选择一个值,以改变此元素的不透明度。</h1>
<select onchange="changeopacity(this)" size="5">
    <option />0
    <option />0.2
    <option />0.5
    <option />0.8
    <option selected/>1
    </select>
<script>
    function changeopacity(x) {
        var opacity=x.options[x.selectedIndex].text;
        document.getElementById("p1").style.opacity=opacity;
    }
    </script>
</body>

设置表格样式

有不少属性可用来为table元素设置独特样式。

属性 说明
border-collapse 设置相邻单元格的边框处理样式
border-spacing 设置相邻单元格边框的间距
caption-side 设置表格标题的位置
empty-cells 设置空单元格是否显示边框
table-layout 指定表格的布局样式

border-collapse属性用来控制table元素相邻单元格边框的样式。默认情况下,浏览器为表格绘制了一个边框,同时还为每个单元格绘制了边框,显示出来就是双边框。

border-collapse属性值有:

  • separate:默认值。边框会被分开。不会忽略border-spacingempty-cells属性。

  • collapse:如果可能,边框会合并为一个单一的边框。会忽略border-spacingempty-cells属性。

border-collapse属性值为separate时,border-spacing:用于定义相邻元素边框的间距。语法为:

border-spacing:<length1>  //定义的是水平和垂直间距。
border-spacing:<length1> <length2>  //第一个设置水平间距,而第二个设置垂直间距。

chap2-61.html

<head><style type="text/css">table{border-collapse:collapse} 
th,td{padding: 2px} </style>
</head>
<body>
<table border="1" id="t1">
    <tr><th>Rank</th><th>Name</th><th>Color</th><th>Size</th></tr>
    <tr><th>Favorite:</th><td>Apples</td><td>Green</td><td>Medium</td></tr>
    <tr><th>2nd Favorite:</th><td>Oranges</td><td>Orange</td><td>Large</td></tr>
    </table>
<p><button>collapse</button><button>separate</button></p>
<script>
    var buttons=document.getElementsByTagName("button");
    for(var i=0;i<buttons.length;i++){
        buttons[i].onclick=function (e) {
            document.getElementById("t1").style.borderCollapse=e.target.innerHTML;
        if(i=1){
            document.getElementById("t1").style.borderSpacing="10px 20px";
        }
        }
            }
</script>
</body>

empty-cells属性设置是否显示表格中的空单元格(仅用于“分离边框”模式)。其值有:

  • hide:不在空单元格周围绘制边框。

  • show:在空单元格周围绘制边框。默认。

caption-side属性设置表格标题的位置。其值有:

  • top:默认值。把表格标题定位在表格之上。

  • bottom:把表格标题定位在表格之下。

默认情况下,浏览器会根据表格每一列中最宽的单元格设置整列单元格的宽度。这就意味着在能够确定页面布局之前,浏览器必须获取所有的表格内容。

table-layout属性用来显示表格单元格、行、列的算法规则。其值有:

  • fixed:固定表格布局,水平布局仅取决于表格宽度、列宽度、表格边框宽度、单元格间距,而与单元格的内容无关。与自动表格布局相比,允许浏览器更快地对表格进行布局。

  • auto:自动表格布局,列的宽度是由列单元格中没有折行的最宽的内容设定的。此算法有时会较慢,这是由于它需要在确定最终的布局之前访问表格中所有的内容。

chap2-62.html

<head>
<style type="text/css">
table{border-collapse:separate;empty-cells: show;border-spacing: 10px;width: 300px;table-layout: auto}
caption{caption-side: top;font-weight: bold}
th,td{padding: 2px}
</style>
</head>
<body>
<table border="1">
    <caption>Table 1. The fruits I Like</caption>
    <tr>
        <th>Rank</th><th>Name</th><th>Color</th><th>Size</th>
    </tr>
    <tr>
        <th>Favorite:</th><td>Apples</td><td>Green</td><td>Medium</td>
    </tr>
    <tr>
        <th>2nd Favorite:</th><td>Oranges</td><td>Orange</td><td></td>
    </tr>
    </table>
</body>

设置列表样式

list-style属性专门用来设置列表样式,语法为:

list-style: <list-style-type> <list-style-position> <list-style-image>

list-style-type属性设置列表项标记的类型。

list-style-type 说明 list-style-type 说明
none 无标记 disc 实心圆,默认
circle 空心圆 square 实心方块
decimal 数字 decimal-leading-zero 0开头的数字标记(01,02,…)
lower-roman 小写罗马数字(i, ii, …) upper-roman 大写罗马数字(I, II,…)
lower-alpha 小写英文字母 upper-alpha 大写英文字母

list-style-position属性设置在何处放置列表项标记。其值有:

  • inside:列表项目标记放置在文本以内,且环绕文本根据标记对齐。

  • outside:默认值。保持标记位于文本的左侧。列表项目标记放置在文本以外,且环绕文本不根据标记对齐。

list-style-image属性可以将图像用做列表标记。

chap2-63.html

<head>
    <meta charset="UTF-8">
    <title>chap2-63</title>
    <style type="text/css">
        ul.inside{list-style-position: inside;list-style-image: url("pic/CSS3.jpg");}
        ul.outside{list-style-position: outside;list-style-image: url("pic/CSS3.jpg");}
        li{background-color: lightgray}
    </style>
    </head>
<body>
<p>该列表的 list-style-position 的值是 "inside":</p>
<ul class="inside">
    <li>Earl Grey Tea - 一种黑颜色的茶</li>
    <li>Jasmine Tea - 一种神奇的“全功能”茶</li>
    <li>Honeybush Tea - 一种令人愉快的果味茶</li>
    </ul>
<p>该列表的 list-style-position 的值是 "outside":</p>
<ul class="outside">
    <li>Earl Grey Tea - 一种黑颜色的茶</li>
    <li>Jasmine Tea - 一种神奇的“全功能”茶</li>
    <li>Honeybush Tea - 一种令人愉快的果味茶</li>
    </ul>
</body>

设置光标样式

cursor属性用来改变光标的外形。

说明 说明
url 需使用的自定义光标的 URL。 ne-resize 此光标指示矩形框的边缘可被向上及向右移动(北/东)。
default 默认光标(通常是一个箭头) nw-resize 此光标指示矩形框的边缘可被向上及向左移动(北/西)。
auto 默认。浏览器设置的光标。 n-resize 此光标指示矩形框的边缘可被向上(北)移动。
crosshair 光标呈现为十字线。 se-resize 此光标指示矩形框的边缘可被向下及向右移动(南/东)。
pointer 光标呈现为指示链接的指针(一只手) sw-resize 此光标指示矩形框的边缘可被向下及向左移动(南/西)。
move 此光标指示某对象可被移动。 s-resize 此光标指示矩形框的边缘可被向下移动(南)。
e-resize 此光标指示矩形框的边缘可被向右(东)移动。 w-resize 此光标指示矩形框的边缘可被向左移动(西)。
text 此光标指示文本。 wait 此光标指示程序正忙(通常是一只表或沙漏)。
help 此光标指示可用的帮助(通常是一个问号或一个气球)。

chap2-64.html

<head>
<style type="text/css">
span{display: block;width: 300px;height: 50px;line-height:50px;border:medium solid black;text-align:center;margin:20px;float: left}
</style>
</head>
<body>
<p>请把鼠标移动到单词上,可以看到鼠标指针发生变化:</p>
<span style="cursor:auto">Auto</span>
<span style="cursor:crosshair">Crosshair</span>
<span style="cursor:default">Default</span>
<span style="cursor:pointer">Pointer</span>
<span style="cursor:move">Move</span>
<span style="cursor:e-resize">e-resize</span>
<span style="cursor:ne-resize">ne-resize</span>
<span style="cursor:nw-resize">nw-resize</span>
<span style="cursor:n-resize">n-resize</span>
<span style="cursor:se-resize">se-resize</span>
<span style="cursor:sw-resize">sw-resize</span>
<span style="cursor:s-resize">s-resize</span>
<span style="cursor:w-resize">w-resize</span>
<span style="cursor:text">text</span>
<span style="cursor:wait">wait</span>
<span style="cursor:help">help</span>
</body>

JavaScript

基础语法

词法结构

JavaScript是区分大小写的语言。

JavaScript支持2种格式的注释:

// 这里是单行注释
/* 这里是一段注释(这里的注释可以连写多行) */

JavaScript中,标识符用来对变量和函数进行命名。标识符必须以字母、下划线(_)或美元符($)开始。后续的字符可以是字母、数字、下划线或美元符。

JavaScript保留字不能作为标记符,例如:breakdeletefunctionreturntypeofcasedoifswitchvarcatch

JavaScript使用分号(;)将语句分隔开。

类型、变量、运算符和表达式

JavaScript的数据类型分为2类:

  • 原始类型:包括数字、字符串和布尔值。JavaScript中有两个特殊的原始值:null(空)和undefined(未定义)。
  • 对象类型:是属性的集合,每个属性都由“名/值对”构成。

数字、算术运算符

数字:包括整数、浮点数。

算术运算符:加(+)、减(-)、乘(*)、除(/)、求余数(%)、递增(++)、递减(--)、按位异或(^)。

  • 注意:++--运算符的返回值依赖于它相对于操作数的位置。当运算符在操作数之前,称为“前增量”运算符,它对操作数进行增量计算,并返回计算后的值。当运算符在操作数之后,称为“后增量”运算符,它对操作数进行增量计算,但返回未做增量计算的值。

    var i=1,j=++i;  //i和j的值都是2
    var i=1,j=i++;  //i是2,j是1
    
  • ^如果不是出现在正则表达式中,那么其代表按位异或运算符,也可以充当二进制算法。

  • 异或的算法为相同输出0,不同输出1

    a^b a的二进制 b的二进制 运算结果二进制 运算结果十进制
    6^8 0110(三位,不够前面加0) 1000 1110 14
    20^31 10100 11111 01011 11

数学常量

常量 说明
Math.E 常量e,自然对数的底数
Math.LN10 10的自然对数
Math.LN2 2的自然对数
Math.LOG10E e以10为底的对数
Math.LOG2E e以2为底的对数
Math.PI 常量π
Math.SQRT1_2 2的平方根的倒数
Math.SQRT2 2的平方根

数学函数

函数 说明 函数 说明
Math.abs(x) 返回x的绝对值 Math.acos(x) 返回x的反余弦值
Math.asin(x) 返回x的反正弦值 Math.atan(x) 返回x的反正切值
Math.atan2(y,x) 返回从X轴到指定点的角度,y为点的Y坐标,x为点的X坐标 Math.ceil(x) 返回大于或等于x的最接近的整数
Math.cos(x) 返回x的余弦值 Math.exp(x) 返回e的x次方
Math.floor(x) 返回小于或等于x的最接近的整数 Math.log(x) 返回x的自然对数
Math.max(args…) 返回参数中最大的值,参数中可以有多个值 Math.min(args…) 返回参数中最小的值,参数中可以有多个值
Math.pow(x,y) 返回xy次方 Math.random() 返回一个在[0.0,1)之间的随机数
Math.round(x) 返回最接近x的整数 Math.sin(x) 返回x的正弦值
Math.sqrt(x) 返回x的平方根 Math.tan(x) 返回x的正切值

数字相关方法

方法 说明
n.toExponential(digits) 返回以指数记数法表示的n的字符串格式,小数点前有一个数字,小数点后有digits个数字
n.toFixed(digits) 返回n的字符串格式,不使用指数记数法,在小数点后有指定的digits个数字
n.toLocaleString() n转换为本地格式的字符串
n.toPrecision(prec) 返回一个包含prec位有效数字的数字字符串,如果prec足够大,包括当前数字的所有整数部分,则返回值与toFixed方法一致。其他情况下,将使用指数记数法,小数点前有一个数字,小数点后有prec-1个数字
n.toString() n转换为字符串
Number(object) 把对象的值转换为数字。如果参数是Date对象,Number()返回从1970年1月1日至今的毫秒数。如果对象的值无法转换为数字,那么Number()函数返回NaN

字符串

由单引号或双引号括起来的字符序列。由单引号定界的字符串中可以包含双引号,由双引号定界的字符串中也可以包含单引号。

  • 注意:当使用单引号来定界字符串时,需注意英文中的缩写(can't)。因为撇号和单引号是同一个字符,所以必须使用转义字符(\)来转义,例如'can\'t'

JavaScript的内置功能之一就是字符串的连接。连接运算符为“+”。例如:

var msg="hello, "+"world";   //生成字符串“hello, world”

length属性可以确定一个字符串的长度,例如:msg.length

JavaScript中用“>”或“<”操作符比较字符串大小时,它们只会比较这些字符的Unicode编码,而不考虑本地的顺序。

字符串类型的大小判断是一个字符和一个字符的比较,只要有字符不同就停止继续判断并返回比较结果。例如:"aBc"<"ab";

localeCompare方法可以实现汉字按拼音排序。

字符集 范围 Unicode编码(16进制) Unicode编码(10进制)
数字 0~9 30~39 48~57
大写字母 A~Z 41~5A 65~90
小写字母 a~z 61~7A 97~122
基本汉字 ~ 4E00~9FA5 19968~40869

字符串相关方法

方法 说明 方法 说明
s.charAt(n) 返回字符串s的第n个字符,从0开始 s.concat(value,…) 返回由每个参数连接为s而组成的新的字符串。 s="hello"; s.concat("","world","!");
s.indexOf(s1 [,start]) 返回在sstart位置之后,s1第一次出现的位置,如果没有找到则返回-1 s.lastIndexOf(s1[,start]) 返回s1在字符串sstart位置之前最后一次出现的位置,如果没有找到则返回-1。其从s的结尾开始搜索到开头
s.trim() 去掉开头和结尾处的空白字符 s.match(s1) 在字符串内检索指定的值,若找到,则返回s1,若没有找到,则返回null
s.replace(s1,s2) 用于在s中用s2替换s1 s.search(s1) 返回第一个s1相匹配的子串的起始位置。如果没有找到任何匹配的子串,则返回 -1
s.slice(start,end) 返回从start位置开始,直到但不包含end位置的所有字符 s.split(delimiter) 通过delimiters切分成一个数组。
s.substr(start,length) 返回从start位置开始的length个字符 s.substring(start,end) 返回从start位置开始,直到但不包含end位置的所有字符
s.toLocaleLowerCase() 以本地化的方式将s转为小写 s.toLocaleUpperCase() 以本地化的方式将s转为大写
s.toLowerCase() s转为小写 s.toUpperCase() s转为大写
s.localeCompare(s1[,locale]) ss1小,返回一个小于0的数,若ss1大,返回一个大于0的数,若相同,返回0。可用于汉字按拼音排序的规则,例如"张三">"李四"。注意:Chrome浏览器在使用时需用: s.localeCompare(s1,"zh")locale包含一种或多种语言或区域设置标记的区域设置字符串数组。如果包含多个区域设置字符串,请以降序优先级对它们进行排列,确保首个条目为首选区域位置。如果省略此参数,则使用JavaScript运行时的默认区域设置。

布尔值、逻辑运算符、关系运算符、nullundefined

布尔值:这个类型只有两个值,保留字truefalse

逻辑运算符:&&(逻辑与)、||(逻辑或)、!(逻辑非)

关系运算符:==(等于)、<(小于)、>(大于)、<=(小于等于)、>=(大于等于)、!=(不等于)

null是JavaScript语言的关键字,表示一个特殊值,常用来描述“空值”。

undefined是变量的一种取值,表明变量没有初始化。如果函数没有返回值,则返回undefined

变量

在JavaScript中,使用一个变量之前应先声明。变量是用关键字var来声明的,例如:

var i,j;        //通过一个var声明多个变量
var i=0,j=0;    //可以将变量的初始赋值和变量声明合写在一起

变量的作用域:

  • 全局变量:声明在函数外部的变量

  • 局部变量:声明在函数内部的变量。函数内声明的所有变量在函数体内始终是可见的。这意味着变量在声明之前甚至已经可见。JavaScript的这个特性被非正式地称为声明提前(hoisting),例如:

    var scope="global";
    function f() {
        console.log(scope);     //输出“undefined”,而不是“global”
        var scope="local";      //变量在这里赋初始值,但变量本身在函数体内任何地方均是有定义的
        console.log(scope);     //输出“local”
        }
    

赋值

赋值表达式:JavaScript使用“=”运算符来给变量或者属性赋值。

带操作的赋值运算:

运算符 示例 等价于
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
^= a^=b a=a^b

语句

条件语句

通过判断指定表达式的值来决定执行还是跳过某些语句。JavaScript中基本的条件语句有2种:

  • if语句,其有两种形式:

    // 1
    if (条件)
      语句1;
    [else
     语句2;]
    
    //2
    if (条件){
        语句块1;
        }
    [else{
        语句块2;
        }]
    

chap3-1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap3-1</title>
    </head>
<body>
<form>
    <span>The Grade:</span><input type="text" id="Grade">
    </form>
<script>
    document.getElementById("Grade").onkeydown=function (e) {
        if(e.keyCode==13){
            if(e.target.value>=60)
                alert("成绩及格");
            else
                alert("成绩不及格");
        }
    }
    </script>
</body>
</html>
  • switch语句,其形式为:

    switch (expression){
        case e1:    //如果expression==e1,则执行语句块1
            语句块1;
            break;  //停止执行switch语句
        case e2:    //如果expression==e2,则执行语句块2
            语句块2;
            break;
        case en:    //如果expression==en,则执行语句块n
            语句块n;
            break;
        default:    //如果所有的条件都不匹配,则执行语句块n+1
            语句块n+1;
            break;
            }
    

    chap3-2.html

    <body><form><span>The Grade:</span><input type="text" id="Grade"></form>
    <script>document.getElementById("Grade").onkeydown=function (e) {
            if(e.keyCode==13){
                var Grank=Math.floor(document.getElementById("Grade").value/10);
                switch (Grank){
                    case 10:
                        alert("优秀");
                        break;
                    case 9:
                        alert("优秀");
                        break;
                    case 8:
                        alert("良好");
                        break;
                    case 7:
                        alert("中等");
                        break;
                    case 6:
                        alert("及格");
                        break;
                    default:
                        alert("不及格");
                        break;
                }}} </script></body>
    

循环语句

可以让一部分代码重复执行。JavaScript中有4种循环语句:

  • while语句

    // 1
    while (条件)
        语句;
    // 2
    while (条件){
        语句块;
        }
    

    chap3-3.html

    <body>
    <form>
        <span>阶乘:</span><input type="text" id="jc">
        </form>
    <script>
        var o=document.getElementById("jc");
        o.onkeydown=function (e) {
            if(e.keyCode==13){
                var m=n=o.value;
                var result=1;
                while(n>0){
                    result*=n;
                    n=n-1;
                }
                alert(m+"!="+result);
            }
        }
        </script>
    </body>
    </html>
    
  • do/while语句

    // 1
    do
        语句;
        while(条件);
    // 2
    do{
        语句块;
        }while(条件);
    

    chap3-4.html

    <body>
    <form>
        <span>阶乘:</span><input type="text" id="jc">
        </form>
    <script>
        var o=document.getElementById("jc");
        o.onkeydown=function (e) {
            if(e.keyCode==13){
                var m=n=o.value;
                var result=1;
                do{
                    result*=n;
                    n--;
                }while(n>0);
                alert(m+"!="+result);
            }
        }
        </script>
    </body>
    
  • for语句

    for(initialize;test;increment){
        statements;
        }
    

    chap3-5.html

    <body>
    <form>
        <span>阶乘:</span><input type="text" id="jc">
        </form>
    <script>
        var o=document.getElementById("jc");
        o.onkeydown=function (e) {
            if(e.keyCode==13){
                var m=o.value;
                var result=1;
                for(var i=1;i<=m;i++){
                    result*=i;
                }
                alert(m+"!="+result);
            }
        }
        </script>
    </body>
    
  • for/in语句

    for(variable in object){
        statements;
        }
    

    chap3-6.html

    <script>
        var a="1,2,3,4,5";
        var arr=a.split(",");
        var sum=0;
        for(var i in arr){
            sum+=Number(arr[i]);
        }
        alert(a+"中值的和为:"+sum);
    </script>
    

跳转语句

可以使得JavaScript的执行从一个位置跳转到另一个位置。

  • break语句是跳转到循环或者其他语句的结束。
  • continue语句是终止本次循环的执行并开始下一次循环的执行。

chap3-7.html

<script>
    var sumb=sumc=0;
    for(var i=1;i<=100;i++){
        sumb+=i;
        if(i==50)
            break;
    }
    for(var i=1;i<=100;i++){
        if(i==50)
            continue;
        sumc+=i;
    }
    alert("break的结果:"+sumb+"\n"+"continue的结果:"+sumc);
</script>

标签语句

标签是由语句前的标识符和冒号组成:identifier:statement

通过给语句定义标签,就可以在程序的任何地方通过标签名引用这条语句。breakcontinue是JavaScript中唯一可以使用语句标签的语句。

break|continue identifier;

mainloop: while(j<=100){
    j++;
    continue mainloop;  //跳转到下一次循环
    }
alert("j的值为:"+j);
mainloop: while(j<=100){
   j++;
   break mainloop;
   }
alert("j的值为:"+j);   //break语句跳转至此处

注意:不管continue语句带不带标签,它只能在循环体内使用。

return语句

可以指定函数调用后的返回值。return expression;

function squre(x) {
   return x*x;
   }
document.writeln("2的平方等于:"+squre(2)+"<br>");

异常处理语句

所谓异常(exception)是当发生了某种异常情况或错误时产生的一个信号。抛出异常就是用信号通知发生了错误或异常情况。捕获异常是指处理这个信号,即采取必要的手段从异常中恢复。

throw语句可以抛出异常:throw expression;

try/catch/finally语句可以捕获异常:

try{
    //通常来讲,这里的代码会从头执行到尾而不会产生问题,但有时会抛出一个异常,要么是由throw语句直接抛出异常,要么是通过调用一个方法间接抛出异常
    }
catch(e){
    //当且仅当try语句块抛出了异常,才会执行这里的代码。这里可以通过局部变量e来获得对Error对象或者抛出的其它值的引用,这里的代码块可以基于某种原因处理这个异常,也可以忽略这个异常,还可以通过throw语句重新抛出异常。
    }
finally{
    /*不管try语句块是否抛出了异常,这里的逻辑总是会执行,终止try语句块的方式有:
    1)正常终止,执行完语句块的最后一条语句
    2)通过break、continue或return语句终止
    3)抛出一个异常,异常被catch从句捕获
    4)抛出一个异常,异常未被捕获,继续向上传播
    */
    }

chap3-8.html

<script>
    function jc(x) {
        if(x<0||x>10) throw new Error("x的值不能为负");
        for(var res=1;x>1;res*=x,x--);
        return res;
    }
    var grade=Number(prompt("请输入一个正整数:",""));
    try{
       alert(grade+"!="+jc(grade));
    }
    catch (e){
        alert(e);
        var grade=Number(prompt("请输入一个正整数:",""));
        if(grade>10) throw new Error("x的值不能超过10");
        alert(grade+"!="+jc(grade));
    }
    finally {
        alert("x的范围为1-10之间");
    }
</script>

数组

数组是值的有序集合。每个值叫做一个元素,而每个元素在数组中有一个位置,以数字表示,称为索引。

JavaScript数组是无类型的:数组元素可以是任意类型,并且同一个数组中的不同元素也可能有不同的类型。

创建

创建数组有2种方式:

  • 数组直接量:

    var empty=[];   //没有元素的数组
    var primes=[1,2,3,4,5];     //有5个数值的数组
    var misc=[1.1,true,"a"];    //3个不同类型的元素
    var base=1024;
    var table=[base,base+1,base+2];     //值可以是表达式
    var b=[{x:1,y:2},primes];   //值还可以对象或其它数组
    

    如果省略数组直接量中的某个值,省略的元素将被赋予undefined值:

    var count=[1,,3];   //数组有3个元素,中间的那个元素值为undefined
    var undefs=[,,];    //数组有2个元素,都是undefined
    

    数组直接量的语法允许有可选的结尾的逗号,故[,,]只有两个元素,而非三个。

  • 调用构造函数Array(),其有2种形式:

    • 调用时没有参数:var a=new Array();

      该方法创建一个没有任何元素的空数组,等同于数组直接量[]

    • 调用时有一个数值参数,它指定长度:var a=new Array(10);

      当预先知道所需元素个数时,这种形式的Array()构造函数可以用来预分配一个数组空间。此时数组中没有存储值,甚至数组的索引属性“0”、“1”等还未定义。

      我们可以用new Array()显示指定两个或多个数组元素或者数组的一个非数值元素:

      var a=new Array(5,4,"testing");
      

读写

数组元素的读与写:使用[]操作符来访问数组中的一个元素。

var a=["hello"];    //从一个元素的数组开始
var value=a[0];     //读第0个元素
a[1]=3.14;          //写第1个元素
i=2;
a[i]=3;             //写第2个元素
document.write(a.length);

JavaScript中数组的特别之处在于,当使用小于232的非负整数作为索引时,数组会自动维护其length属性值,如上,创建仅有一个元素的数组,然后在索引12处分别进行赋值,则数组的长度变为3

注意:JavaScript中数组索引仅仅是对象属性名的一种特殊类型,这意味着数组没有“越界”错误的概念。当试图查询对象中不存在的属性时,不会报错,只会得到undefined值。

稀疏数组

就是包含从0开始的不连续索引的数组。稀疏数组length属性大于元素的个数。可以用Array()构造函数或简单地指定数组的索引值大于当前的数组长度来创建稀疏数组。

a=new Array(5);     //数组没有元素,但是a.length是5
a[1000]=0;      //赋值添加一个元素,但是设置length为1001

足够稀疏的数组通常在实现上比稠密的数组更慢,内存利用率更高,在这样的数组中查找元素的时间更长。

元素的添加

数组元素的添加有3种方式:

  • 为新索引赋值:

    var a=[];   //开始是一个空数组
    a[0]="zero";    //然后向其中添加元素
    a[1]="one";
    
  • 使用push()方法在数组末尾添加一个或多个元素:

    var a=[];   //开始是一个空数组
    a.push("zero");    //在末尾添加一个元素
    a.push("one","two");    //在末尾添加两个元素
    
  • 使用unshift()方法在数组头部添加一个或多个元素:

    var a=[];   //开始是一个空数组
    a.unshift("two");    //在头部添加一个元素
    a.unshift("zero","one");    //在头部添加两个元素
    

元素的删除

数组元素的删除有3种方式:

  • 使用delete运算符删除:

    对一个数组使用delete不会修改数组的length属性,也不会将元素从高索引处移下来填充已删除属性留下的空白。

    var a=[1,2,3];
    delete a[1];    //a在索引1的位置不再有元素
    
  • 使用pop()方法删除数组末尾的元素:

    该方法减少数组的长度。

    var a=[1,2,3];
    a.pop();    //删除a尾部的元素
    
  • 使用shift()方法在数组头部删除一个或多个元素:

    该方法减少数组的长度,并将所有随后的元素下移一个位置来填补数组头部的空缺。

    var a=[1,2,3];
    a.shift();    //删除a头部的元素
    

多维数组

JavaScript不支持真正的多维数组,但可以用数组的数组来近似。

chap3-9.html

<head><style>
span{display: inline-block;width: 80px;height: 60px;font-size: xx-large}</style>
</head>
<body>
<script>
    var table=new Array(10);    //表格有10行
    for(var i=0;i<table.length;i++)
        table[i]=new Array(10);     //每行有10列
    //初始化数组
    for(var row=0;row<table.length;row++){
        for(var col=0;col<table[row].length;col++){
            table[row][col]=row*col;
        }
    }
    //输出数组元素值
    for(var row=0;row<table.length;row++){
        for(var col=0;col<table[row].length;col++){
            document.write("<span>"+table[row][col]+"</span>");
        }
        document.write("<br>");
    }
    </script>
</body>

数组方法

join():将数组中所有元素都转化为字符串并连接在一起,返回最后生成的字符串。可以指定一个可选的字符串在生成的字符串中来分隔数组的各个元素。如果不指定分隔符,默认使用逗号。

var a=[1,2,3];  //创建一个包含三个元素的数组
var str=a.join();   //str的值为“1,2,3”
str=a.join(" ");    //str的值为“1 2 3”

reverse():将数组中的元素颠倒顺序,返回逆序的数组。

var a=[1,2,3];  //创建一个包含三个元素的数组
a.reverse();
for(var i=0;i<a.length;document.write(a[i]+"<br>"),i++);

sort():将数组中的元素排序并返回排序后的数组,语法为:arrayObject.sort([sortby])

  • 如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。

    var a=["banana","cherry","apple"];
    a.sort();
    for(var i=0;i<a.length;document.write(a[i]+"<br>"),i++);
    var b=[33,4,1111,222];
    b.sort();   //输出结果:1111 222 33 4
    for(var i=0;i<b.length;document.write(b[i]+"<br>"),i++);
    
  • 如果想按照其他标准进行排序,就需要提供比较函数(sortby),该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数ab,其返回值如下:

    • a小于b,在排序后的数组中a应该出现在b之前,则返回一个小于0的值。
    • a等于b,则返回0
    • a大于b,则返回一个大于0的值。

chap3-10.html

<script>
    var a=["banana","cherry","apple"];
    a.sort();
    for(var i=0;i<a.length;document.write(a[i]+"<br>"),i++);
    var b=[33,4,1111,222];
    b.sort();   //输出结果:1111 222 33 4
    for(var i=0;i<b.length;document.write(b[i]+"<br>"),i++);
    b.sort(function (m,n) {
        return m-n;     //按由小到大的顺序排列
    });
    for(var i=0;i<b.length;document.write(b[i]+"<br>"),i++);
</script>

concat():创建并返回一个新数组,它的元素包括调用concat()的原始数组的元素和concat()的每个参数。如果这些参数中的任何一个自身是数组,则连接的是数组的元素,而非数组本身。

注意:concat()不会递归扁平化数组的数组。concat()也不会修改调用的数组。

chap3-11.html

<head>
    <meta charset="UTF-8">
    <title>chap3-11</title>
    <style>
        span{display: inline-block;width: 80px;height: 60px;font-size: xx-large}
        span#s1{display: block}
    </style>
    </head>
<body>
<script>
    var a=[1,2,3];
    var b=a.concat(4,5);    //返回[1,2,3,4,5]
    b=a.concat([4,5],[6,7]);      //返回[1,2,3,4,5,6,7]
    b=a.concat([4,[5,[6,7]]]);      //返回[1,2,3,4,[5,[6,7]]]
    for(var i=0;i<b.length;i++){
        if(Array.isArray(b[i]))
            for(var j=0;j<b[i].length;document.write("<span>"+b[i][j]+"</span>"),j++);
        else
            document.write("<span id='s1'>"+b[i]+"</span>");
    }
    </script>
</body>

slice()方法返回一个新的数组,包含从start到end (不包括该元素)的arrayObject中的元素。其语法格式为:

arrayObject.slice(start,end)

  • start:必需。规定从何处开始选取。如果是负数,那么它规定从数组尾部开始算起的位置。也就是说,-1指最后一个元素,-2指倒数第二个元素,以此类推。

  • end:可选。规定从何处结束选取。该参数是数组片断结束处的数组下标。如果没有指定该参数,那么切分的数组包含从start到数组结束的所有元素。如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。

var a=[1,2,3,4,5];
document.write(a.slice(0,3)+"<br>");    //返回[1,2,3]
document.write(a.slice(3)+"<br>");      //返回[4,5]
document.write(a.slice(1,-1)+"<br>");   //返回[2,3,4]

splice()方法向/从数组中添加/删除项目,然后返回被删除的项目。其语法格式为:

arrayObject.splice(index,howmany,item1,.....,itemX)

  • index:必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。

  • howmany:必需。要删除的项目数量。如果设置为0,则不会删除项目。

  • item1,…,itemX:可选。向数组添加的新项目。

  • splice()方法可删除从index处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。

  • 如果从arrayObject中删除了元素,则返回的是含有被删除的元素的数组。

chap3-12.html

<script>
    var a=[1,2,3,4,5];
    document.write(a.slice(0,3)+"<br>");    //返回[1,2,3]
    document.write(a.slice(3)+"<br>");      //返回[4,5]
    document.write(a.slice(1,-1)+"<br>");   //返回[2,3,4]
    a.splice(2,0,6);
    document.write(a+"<br>");   //返回[1,2,6,3,4,5]
    a.splice(2,1);
    document.write(a+"<br>");   //返回[1,2,3,4,5]
    a.splice(2,1,6);
    document.write(a+"<br>");   //返回[1,2,6,4,5]
    a.splice(2,3,3);
    document.write(a+"<br>");   //返回[1,2,3]
    a.splice(3,0,4,5);
    document.write(a+"<br>");   //返回[1,2,3,4,5]
</script>

函数

函数是这样的一段JavaScript代码,它只定义一次,但可能被执行或调用任意次。

JavaScript函数是参数化的:函数的定义会包括一个称为形参(parameter)的标识符列表,这些参数在函数体中像局部变量一样工作。函数调用会为形参提供实参(argument)的值。函数使用它们实参的值来计算返回值,成为该函数调用表达式的值。

除了实参之外,每次调用还会拥有另一个值,即本次调用的上下文(context),这就是this关键字的值。如果函数挂载在一个对象上,作为对象的一个属性,就称它为对象的方法。当通过这个对象来调用函数时,该对象就是此次调用的上下文,也就是该函数的this的值。

JavaScript的函数可以嵌套在其他函数中定义,这样就构成了一个闭包(closure)。

定义

函数使用function关键字来定义,它可以用在:

  • 函数声明语句

    在函数声明语句中:

    • function关键字后的函数名称是函数声明语句必需的部分。
    • 一对圆括号,其中包含由0个或者多个用逗号隔开的形参组成的列表。
    • 一对花括号,其中包含0条或多条JavaScript语句。

    这些语句构成了函数体,一旦调用函数,就会执行这些语句。

    function jc(x) {
        var result=1;
        for(var i=1;i<=x;i++){
            result*=i;
        }
        return result;
        }
    var a=Number(prompt("请输入一个正整数:",""));
    document.write(jc(a)+"<br>");
    
  • 函数定义表达式

    对于函数定义表达式来说,函数名称是可选的,如果存在,该名字只存在于函数体中,并指代该函数对象本身。

    var square=function(x) {return x*x;};   //定义时函数名称省略
    document.write(square(a)+"<br>");       //调用时使用变量名称(实参)形式
    var f=function fact(x) {                //定义时可以包含函数名称
        if (x<=1)
            return 1;
        else
            return x*fact(x-1);
            }
    document.write(f(a)+"<br>");            //调用时使用变量名称(实参)形式
    

如同变量,函数声明语句“被提前”到外部脚本或外部函数作用域的顶部,所以以这种方式声明的函数,可以被在它定义之前出现的代码所调用。

但是,对于函数定义表达式而言,就另当别论了,为了调用一个函数,必须要能引用它,而要使用一个以表达式方式定义的函数之前,必须把它赋值给一个变量。变量的声明提前了,但给变量赋值是不会提前的,所以,以表达式方式定义的函数在定义之前无法调用。

chap3-13.html

<script>
    var a=Number(prompt("请输入一个正整数:",""));
    document.write(jc(a)+"<br>");
    function jc(x) {
        var result=1;
        for(var i=1;i<=x;i++){
            result*=i;
        }
        return result;
    }
    var square=function(x) {return x*x;};   //定义时函数名称省略
    document.write(square(a)+"<br>");       //调用时使用变量名称(实参)形式
    var f=function fact(x) {                //定义时可以包含函数名称
        if (x<=1)
            return 1;
        else
            return x*fact(x-1);
    }
    document.write(f(a)+"<br>");            //调用时使用变量名称(实参)形式
</script>

调用

有4种方式来调用JavaScript函数:

  • 作为函数调用:var a=jc(10);

  • 作为方法调用:var b=Math.floor(3.2);

    方法调用和函数调用有一个重要的区别,即:调用上下文。this关键字只能出现在函数中,当然在全局作用域中是个例外。

    全局作用域中this指向全局对象(全局对象在浏览器这个环境中指window)。

    如果this出现在函数中,其指向的依据就是函数的执行环境而不是声明环境。换句话说,this永远指向所在函数的所有者,当没有显示的所有者的时候,那么this指向全局对象。

    各种情况下的this的具体指向:

    • 在全局作用域中this指向为全局对象windowdocument.write(this+ "<br>");

    • 函数作为某个对象的成员方法调用时this指向该对象。

      chap3-14.js

      var name="zhangsan";
      var obj={
          name:"lizi",
          getName:function () {
              document.write(this.name + "<br>");
          }
          }
      obj.getName();      //输出lizi
      
    • 函数作为函数直接使用时this指向全局对象。

      chap3-14.js

      var name="zhangsan";
      var obj={
          name:"lizi",
          getName:function () {
              document.write(this.name + "<br>");
          }
          }
      var nameGet=obj.getName;
      nameGet();          //输出zhangsan
      
    • 函数作为构造函数调用时this指向用该构造函数构造出来的新对象。

      chap3-14.js

      var name="zhangsan";
      var obj1=function (x,y) {
          this.name=x+y;
          }
      obj1.prototype.getName=function () {
          document.write(this.name + "<br>");
          }
      var myObj=new obj1("wang","er");
      myObj.getName();      //输出wanger
      
    • call()apply()bind()方法可以改变函数执行时候的this指向。

      function Sister() {
          this.age=18;
          this.sayAge=function () {document.write("Age:"+this.age+ "<br>");}
          }
      function Brother() {
          this.age=25;
          this.sayAge=function () {document.write("Age:"+this.age+ "<br>");}
          }
      var sis=new Sister();
      var bro=new Brother();
      sis.sayAge.call(bro);   //输出"Age:25"
      
  • 作为构造函数调用

    如果函数或者方法调用之前带有关键字new,它就构成构造函数调用。var myObj=new obj1("wang","er");

    构造函数调用创建和初始化一个新的对象myObj,并将这个对象用做其调用上下文,因此构造函数可以使用this关键字来引用这个新创建的对象。myObj对象继承自构造函数的prototype属性。

  • 间接调用

    call()apply()方法可以看做是某个对象的方法,通过调用方法的形式来间接调用函数。

    他们的用途相同,都是在特定的作用域中调用函数。

    接收参数方面不同,apply()接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。call()方法第一个参数与apply()方法相同,但传递给函数的参数必须列举出来。

    chap3-14.js

    window.firstName="San";
    window.lastName="Zhang";
    var myObject={firstName:"my",lastName:"Object"};
    function HelloName() {document.write(this.firstName+" "+this.lastName+ "<br>");}
    HelloName.call(window);     //输出"San Zhang"
    HelloName.call(this);      //输出"San Zhang"
    HelloName.call(myObject);   //输出"my Object"
    
    function sum(m,n) {
        return m+n;
        }
    document.write(sum.call(window,10,10)+ "<br>");     //输出20
    document.write(sum.apply(window,[10,20])+ "<br>");  ////输出30
    

实参和形参

JavaScript中的函数定义并未指定函数形参的类型,函数调用也未对传入的实参值做任何类型检查。实际上,JavaScript函数调用甚至不检查传入形参的个数。

可选形参:当调用函数的时候传入的实参比形参个数少时,剩下的形参都将设置为undefined值。因此在调用函数时形参是否可选以及是否可以省略应当保持较好的适应性。为了做到这一点,应当给省略的参数赋一个合理的默认值。

  • 注意:当用这种可选形参来实现函数时,需要将可选形参放在形参列表的最后。

chap3-15.js

function int(x,type) {
    if(type===undefined) return Math.floor(x);
    if(type===1) return Math.floor(x);
    if(type===2) return Math.ceil(x);
    if(type===3) return Math.round(x);
    }
document.write("3.4默认去尾法取整:" +int(3.4)+"<br>");
document.write("3.4去尾法取整:" +int(3.4,1)+"<br>");
document.write("3.4进位法取整:" +int(3.4,2)+"<br>");
document.write("3.4四舍五入取整:" +int(3.4,3)+"<br>");

可变长的实参列表(实参对象):当调用函数的时候传入的实参个数超过函数定义时的形参个数时,没有办法直接获得未命名值的引用。参数对象解决了这个问题。

  • 实参对象有一个重要的用处就是:让函数可以操作任意数量的实参。

  • 假设定义了函数f,它的形参只有一个x。如果调用f时传入两个实参,第一个实参可以通过形参名x来获得,也可以通过arguments[0]来得到;第二个实参只能通过arguments[1]来得到。此外,和数组一样,arguments.length属性返回实参的个数。

  • 注意:arguments不是数组,它是一个实参对象。每个实参对象都包含以数字为索引的一组元素以及length属性。

chap3-15.js

function max() {
    var max=Number.NEGATIVE_INFINITY;   //NEGATIVE_INFINITY 表示负无穷大
    for(var i=0;i<arguments.length;i++){
        if(arguments[i]>max) max=arguments[i];
    }
    return max;
    }
var largest=max(1,10,100,2,3,1000,4,5,10000,6);
document.write("最大值为:"+largest+"<br>");

将对象属性用做实参:当一个函数包含超过三个形参时,对于程序员来说,要记住调用函数中实参的正确顺序很难。最好通过名/值对的形式来传入参数,这样参数的顺序就无关紧要了。为了实现这种风格的方法调用,定义函数时,传入的实参都写入一个单独的对象中,在调用的时候传入一个对象,对象中的名/值对是真正需要的实参数据。

chap3-15.js

function arraycopy(from,from_start,to,to_start,length) {
    for(var i=to_start;i<to_start+length;i++){
        to[i]=from[from_start+i-to_start];
    }
    }
function easycopy(args) {
    arraycopy(args.from,
        args.from_start||0,     //这里设置了默认值
        args.to,
        args.to_start||0,       //这里设置了默认值
        args.length
    );
    }
var a=[1,2,3,4],b=[5,6,7,8];
easycopy({from:a, to:b, to_start:2, length:4});
for(var i=0;i<b.length;i++){document.write(b[i]+"<br>");}

作为值的函数

在JavaScript中,函数不仅是一种语法,也是值,也就是说,可以将函数赋值给变量。

chap3-16.js

function squre(x) {return x*x;}
var s=squre;    //现在s和squre指代同一个函数
document.write(squre(4)+"<br>");
document.write(s(4)+"<br>");

除了可以将函数赋值给变量,同样可以将函数赋值给对象的属性。

chap3-16.js

var o={square:squre};
var x=o.square(16);
document.write(x+"<br>");

函数甚至不需要带名字,当把它们赋值给数组元素时:

chap3-16.js

var a=[function (x) {return x*x},20];
document.write(a[0](a[1])+"<br>");

作为命名空间的函数

JavaScript中变量的作用域有全局变量和局部变量2种。在JavaScript中是无法声明只在一个代码块内可见的变量的,基于这个原因,我们常常简单地定义一个函数用做临时的命名空间,在这个命名空间内定义的变量都不会污染到全局命名空间。

function mymodule() {
    //模块代码,这个模块所使用的所有变量都是局部变量,而不是污染全局命名空间
    }
mymodule();     //不要忘了还要调用这个函数

这段代码仅仅定义了一个单独的全局变量:名叫“mymodule”的函数。这样还是太麻烦,可以直接定义一个匿名函数,并在单个表达式中调用它:

(function () {
 //模块代码
}());   //结束函数定义并立即调用它

闭包

出于种种原因,我们有时候需要得到函数内的局部变量。闭包可以捕捉到局部变量(和参数),并一直保存下来。闭包就是一个函数引用另外一个函数的变量,因为变量被引用着所以不会被回收,因此可以用来封装一个私有变量。这是优点也是缺点,不必要的闭包只会徒增内存消耗!

chap3-17.js

var scope="global scope";       //全局变量
function checkscope() {
    var scope="local scope";    //局部变量
    function f() {return scope;}    //在作用域中返回这个值
    return f();
    }
var a=checkscope();
document.write(a+"<br>")

对象

对象是一种复合值,它将很多值聚合在一起,可通过名字访问这些值。对象也可看作是属性的无序集合,每个属性都是一个名/值对。属性名是字符串,因此我们可以把对象看成是从字符串到值的映射。

对象除了可以保持自有的属性外,还可以从一个称为“原型”的对象继承属性。

除了字符串、数字、truefalsenullundefined之外,JavaScript中的值都是对象。

除了包含属性之外,每个对象还拥有三个相关的对象特性:

对象的原型(prototype)指向另一个对象,本对象的属性继承自它的原型对象。

对象的类(class)是一个标识对象类型的字符串。

对象的扩展标记(extensible flag)指明了(在ECMAScript 5中)是否可以向该对象添加新属性。

JavaScript对象的类别

  • 内置对象:是由ECMAScript规范定义的对象或类。例如,数组,函数,日期和正则表达式。

  • 宿主对象:是由JavaScript解释器所嵌入的宿主环境(比如Web浏览器)定义的。客户端JavaScript中表示网页结构的HTMLElement对象均是宿主对象。

  • 自定义对象:是由运行中的JavaScript代码创建的对象。

创建对象

创建对象(3种方式):

  • 对象直接量:是由若干属性名/值

    var empty={};    //空对象,没有任何属性
    var point={x:0,y:0};    //两个属性
    var book={
        "main title":"JavaScript",      //属性名字里有空格,必须用字符串表示
        "sub-title":"The Definitive Guide",     //属性名字里有连字符,必须用字符串表示
        "for":"all audiences",      //"for"是保留字,因此必须用引号
        author:{            //这个属性的值是一个对象
            firstname:"Shulin",
            lastname:"Chen"
        }
    };
    
  • 通过new创建对象:new关键字创建并初始化一个新对象,new后跟随一个函数调用。这里的函数称作构造函数。例如:

    var author=new Object(); //创建一个空对象
    author.firstname="Shulin";
    author.lastname="Chen";
    
    var mycars=new Array();
    mycars[0]="Saab";
    mycars[1]="Volvo";
    
    var today = new Date();  //Date 对象自动使用当前的日期和时间作为其初始值。
    
  • Object.create(proto[, propertiesObject]) 是ECMAScript 5中提出的一种新的对象创建方式,第一个参数是要继承的原型,也可以传一个null,第二个参数是对象的属性描述符,这个参数是可选的。例如:

    var o1 = Object.create({x:1,y:2});  //o1继承了属性x和y
    var o2 = Object.create(Object.prototype);   //o2和{}以及new Object()一样,创建了一个普通的空对象
    
    • 如果proto参数不是 null 或一个对象,则抛出一个 TypeError 异常。

    • 在ECMAScript 3中可以用类似下面的代码来模拟原型继承:

      chap3-18.js

      //inherit()返回了一个继承自原型对象p的属性的新对象
      //这里使用ECMAScript 5中的Object.create()函数(如果存在的话)
      //如果不存在Object.create(),则退化使用其它方法
      function inherit(p) {
          if(p==null) throw TypeError();      //p是一个对象,但不能是null
          if(Object.create) return Object.create(p);      //如果Object.create()存在,直接使用它
          var t=typeof p;
          if(t!=="object" && t!=="function") throw TypeError();
          function f() {};    //定义一个空构造函数
          f.prototype=p;      //将其原型属性设置为p
          return new f();     //使用f()创建p的继承对象
          }
      //Inherit()函数的其中一个用途就是防止函数无意间(非恶意地)修改那些不受你控制的对象。
      // 不是将对象直接作为参数传入函数,而是将它的继承对象传入函数。
      //如果给继承对象的属性赋值,则这些属性只会影响这个继承对象自身,而不是原始对象。
      var o={x:"don't change this value"};
      changex(inherit(o));
      function changex(obj) {
          obj.x="hello world!";
          document.write(obj.x+"<br>");
          }
      document.write(o.x+"<br>");
      changex(o);
      document.write(o.x+"<br>");
      

属性的查询和设置

JavaScript为属性访问定义了两种语法:

对象名.属性名对象名[表达式]

其中,表达式指定要访问的属性的名称或者代表要访问数组元素的索引。

对于点(.)来说,右侧必须是一个以属性名称命名的简单标识符(不能有空格、连字符等)。点运算符后的标识符不能是保留字,比如book.for是非法的,必须使用方括号的形式访问它们,比如book["for"]

对于方括号([])来说,方括号内必须是一个计算结果为字符串的表达式。其看起来更像数组,只是这个数组元素是通过字符串索引而不是数字索引。这种数组称为“关联数组”。

chap3-19.html

<script>
    var book={
        "main title":"JavaScript",
        "sub-title":"The Definitive Guide",
        "for":"all audiences",
        author:{
            firstname:"Shulin",
            lastname:"Chen"
        }
    };
    var a=[book,4,[5,6]];
    document.write(book.author.firstname+"<br>");   //获得book对象中author的“firstname”属性
    document.write(book["for"]+"<br>");
    document.write(a[0]["main title"]+"<br>");
    document.write(a[2][1]+"<br>");
    book["main title"]="ECMAScript 6";  //给“main title”属性赋值
</script>

JavaScript对象具有自有属性(实例属性),也有一些属性是从原型对象继承而来的(继承属性)。

假设要查询对象q的属性x,如果q中不存在x,则会继续在q的原型对象中查询属性x,如果原型对象中也没有x,但这个原型对象也有原型,那么继续在这个原型对象的原型对象上执行查询,直到找到x或者查找到一个原型是null的对象为止。可以看到,对象的原型属性构成了一个“”,通过这个“”可以实现属性的继承。

chap3-20.html

<head>
    <meta charset="UTF-8">
    <title>chap3-20</title>
    <script src="js/chap3.js"></script>
    </head>
<body>
<script>
    var o={};   //o从Object.prototype继承对象的方法
    o.x=1;      //给o定义一个属性x
    var p=inherit(o);   //p继承o和Object.prototype
    p.y=2;      //给p定义一个属性y
    var q=inherit(p);   //q继承p、o和Object.prototype
    q.z=3;      //给q定义一个属性z
    document.write(q.x+q.y+q.z+"<br>");
    </script>
</body>

假设给对象o的属性x赋值,如果o中已经有属性x(这个属性不是继承来的),那么这个赋值操作只改变这个已有属性x的值。如果o中不存在属性x,那么赋值操作给o添加一个新的属性x。如果之前o继承自属性x,那么这个继承的属性就被新创建的同名属性覆盖了。

属性赋值操作首先检查原型链,以此判定是否允许赋值操作。如果o继承自一个只读属性x,那么赋值操作是不允许的。如果允许属性赋值操作,它也总是在原始对象上创建属性或对已有的属性赋值,而不会去修改原型链。

chap3-20.js

var a={
    get r(){return 1;},
    x:1
    };
var b=inherit(a);   //b继承属性r
b.y=1;              //b定义了个属性
b.x=2;              //b覆盖继承来的属性x
b.r=3;              //r为只读属性,赋值语句无效
document.write(b.r+"<br>"); //输出1
document.write(b.x+"<br>"); //输出2
document.write(a.x+"<br>"); //原型对象没有修改

删除属性

delete运算符可以删除对象的属性。它的操作数是一个属性访问表达式:

delete只是断开属性和宿主对象的联系,而不会去操作对象中的属性。

delete运算符只能删除自有属性,不能删除继承属性,要删除继承属性必须从定义这个属性的原型对象上删除它,而且这会影响到所有继承自这个原型的对象。

chap3-21.js

var book={
    "main title":"JavaScript",
    "sub-title":"The Definitive Guide",
    "for":"all audiences",
    author:{
        firstname:"Shulin",
        lastname:"Chen"
    }
    };
delete book.author;     //book不再有属性author
delete book["main title"];  //book不再有属性"main title"
document.write(book.author+"<br>");
document.write(book["main title"]+"<br>");
var o=Object.create(book);  //o继承了book对象的属性
delete o["for"];    //不能删除继承属性
document.write(book["for"]+"<br>");

检测属性

判断某个属性是否存在于某个对象中可以有3种方式:

in运算符:如果对象的自有属性或继承属性中包含这个属性,则返回true

hasOwnProperty()方法:对象的自有属性返回true,对于继承属性返回false

propertyIsEnumerable()方法:只有检测到是自有属性且这个属性的可枚举性为true时,它才返回true。某些内置属性是不可枚举的。

var o={x:1};
var obj=Object.create(o);
obj.y=2;
"x" in obj;  //输出true
"y" in obj;  //输出true
obj.hasOwnProperty("x");  //输出false
obj.hasOwnProperty("y");  //输出true
obj.propertyIsEnumerable("x");   //输出false
obj.propertyIsEnumerable("y");  //输出true

枚举属性

在JavaScript中,对象的属性分为可枚举和不可枚举之分,它们是由属性的enumerable值决定的。

JavaScript中基本包装类型的原型属性是不可枚举的,如Object, Array, Number等。

Object对象的propertyIsEnumerable()方法可以判断此对象是否包含某个属性,并且这个属性是否可枚举。

for/in循环可以遍历对象中所有可枚举的对象属性(包括对象自有属性和继承的属性)。

Object.keys()方法会返回一个由一个给定对象的自身可枚举属性组成的数组。

Object.getOwnPropertyNames()方法会返回一个由一个给定对象的自身属性组成的数组,包括可枚举和不可枚举的。

chap3-22.js

var po={px:1,py:2};
var o={x:3,y:4};
o.__proto__=po;     //设置o的原型为po
document.write("for/in方法输出结果:<br>");
for(property in o){
    document.write(property+":"+o[property]+"<br>");
}
var propertyArray=Object.keys(o);
document.write("定义枚举属性前Object.keys方法输出结果:<br>");
for(var i=0;i<propertyArray.length;i++){
    document.write(propertyArray[i]+"<br>");
}
Object.defineProperties(o,{
    x:{enumerable:true},
    y:{enumerable:false}
});
propertyArray=Object.keys(o);
document.write("定义枚举属性后Object.keys方法输出结果:<br>");
for(var i=0;i<propertyArray.length;i++){
    document.write(propertyArray[i]+"<br>");
}
propertyArray=Object.getOwnPropertyNames(o);
document.write("定义枚举属性后Object.getOwnPropertyNames方法输出结果:<br>");
for(var i=0;i<propertyArray.length;i++){
    document.write(propertyArray[i]+"<br>");
}

属性gettersetter

对象属性是由名字、值和一组特性(attribute)构成的。在ECMAScript 5中,属性值可以用一个或两个方法替代,这两个方法就是gettersetter。由gettersetter定义的属性称作“存取器属性”(accessorproperty),它不同于“数据属性”(data property)。

数据属性:包含属性的操作特性;如:设置值、是否可枚举等。

特性名称 描述 默认值
value 设置属性的值 undefined
writable 是否可修改属性的值;true:可修改属性的值;false:不可修改属性的值 false
enumerable 是否可枚举属性;true:可枚举,可通过for/in语句枚举属性;false:不可枚举 false
configurable 是否可修改属性的特性;true:可修改属性的特性(如把writablefalse改为true);false:不可修改属性的特性 false

存取器属性:包含属性的操作特性;如:设置值、是否可枚举等。

特性名称 描述 默认值
get 属性的返回值函数 undefined
set 属性的设置值函数;含有一个赋值参数 undefined
enumerable 是否可枚举属性;true:可枚举,可通过for/in语句枚举属性;false:不可枚举 false
configurable 是否可修改属性的特性;true:可修改属性的特性(如把writablefalse改为true);false:不可修改属性的特性 false

存取器也是可以继承的。

chap3-23.html

<script>
    var obj={};
    //添加一个属性,并设置为存取器属性
    Object.defineProperty(obj,"name",{
        get:function () {
            return this._name;  //get和set里的变量不要使用属性,如:属性为name,get和set用的是_name
        },
        set:function (x) {
            if(isNaN(x))    //isNaN() 函数用于检查其参数是否是非数字值。
                this._name=x;
            else
                this._name="name不能为纯数字";
        },
        enumerable:true,
        configurable:true
    });
    obj.name="12";
    document.write(obj.name+"<br>");
    var o=inherit(obj);     //存取器也是可以继承的
    o.name="a12";
    document.write(o.name+"<br>");
</script>

属性的特性

为了实现属性特性的查询和设置操作,ECMAScript 5中定义了一个名为“属性描述符”(property descriptor)的对象,这个对象代表数据属性特性和存取器属性特性。

在使用Object.definePropertyObject.definePropertiesObject.create函数的情况下添加数据属性,writableenumerableconfigurable默认值为false

使用对象直接量创建的属性,writableenumerableconfigurable特性默认为true

Object.getOwnPropertyDescriptor(object,propertyname)可用来获取描述属性特性的描述符对象。其中object为包含属性的对象,必需;propertyname为属性的名称,必需。

chap3-24.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chap3-24</title>
    </head>
<body style="font-size: xx-large">
<script>
    var o1={name:"tom"};
    document.write("对象直接量,属性特性默认为true<br>");
    var desc=Object.getOwnPropertyDescriptor(o1,"name");
    for(var prop in desc)
        document.write(prop+":"+desc[prop]+"<br>");
    var o2=Object.create(null,{
        name:{value:"tom"}
    });
    document.write("通过Object.create创建,属性特性默认为false<br>")
    desc=Object.getOwnPropertyDescriptor(o2,"name");
    for(prop in desc)
        document.write(prop+":"+desc[prop]+"<br>");
        </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,757评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,478评论 1 289
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,540评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,593评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,903评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,329评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,659评论 2 309
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,383评论 0 195
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,055评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,337评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,864评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,227评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,820评论 3 231
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,999评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,750评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,365评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,260评论 2 258

推荐阅读更多精彩内容