Appearance
HTML 头部与脚本
<head> 里放的是"看不见"的页面信息,<script> 用来引入 JavaScript 让页面动起来。
头部 head 包含什么
html
<head>
<meta charset="UTF-8">
<title>页面标题</title>
<meta name="description" content="描述">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>| 内容 | 作用 |
|---|---|
<meta charset> | 编码,中文必备 |
<title> | 浏览器标签栏标题,SEO 重要 |
<meta name="description"> | 页面描述,SEO |
<meta name="viewport"> | 移动端适配 |
<link rel="stylesheet"> | 引入 CSS |
<script src> | 引入 JS |
脚本 script
JavaScript 让网页有交互。三种写法:
html
<!-- 1. 引入外部文件 -->
<script src="app.js"></script>
<!-- 2. 写在 head 里 -->
<head>
<script>
console.log('页面加载了');
</script>
</head>
<!-- 3. 写在 body 末尾(推荐) -->
<body>
<!-- 页面内容 -->
<script>
document.getElementById('btn').onclick = function(){
alert('你点击了按钮');
};
</script>
</body>script 放哪里
- 外部文件:
<script src="...">,标签里不要再写内容 - 位置:操作页面的 JS 建议放
</body>前,避免阻塞加载
一个交互小例子
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>按钮交互</title>
</head>
<body>
<button id="btn">点我</button>
<p id="msg"></p>
<script>
document.getElementById('btn').onclick = function(){
document.getElementById('msg').textContent = '你点了我!';
};
</script>
</body>
</html>点击按钮,下面的文字会变成"你点了我!"。
建议
JS 能做交互后,你的网页就从"静态"升级成"动态"了,这是前端学习的一大步。