这是一份全面的前端技术面试题库,涵盖从基础到高级的前端技术知识点,帮助面试官全面考察候选人的技术能力。
问题1:HTML语义化的作用是什么?请举例说明常用语义化标签。
点击查看答案
答案:
作用:
常用语义化标签:
<header> <!-- 页面或章节的头部 -->
<nav> <!-- 导航链接 -->
<main> <!-- 主要内容 -->
<article> <!-- 独立的文章内容 -->
<section> <!-- 内容区块 -->
<aside> <!-- 侧边栏内容 -->
<footer> <!-- 页面或章节的底部 -->
<figure> <!-- 媒体内容(图片、图表等) -->
<figcaption> <!-- 媒体内容的说明 -->
<time> <!-- 时间 -->
<address> <!-- 联系信息 -->问题2:HTML5新增了哪些重要特性?
点击查看答案
答案:
<audio> 和 <video> 标签问题3:HTML5离线存储与浏览器缓存的区别是什么?
点击查看答案
答案:
问题4:浏览器存储方式有哪些?各有什么特点和限制?
点击查看答案
答案:
cookie(4KB左右):
// 设置cookie
document.cookie = "name=value; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";localStorage(5-10MB):
localStorage.setItem('key', 'value');
localStorage.getItem('key');sessionStorage(5-10MB):
sessionStorage.setItem('key', 'value');
sessionStorage.getItem('key');IndexedDB(存储限制很大):
const request = indexedDB.open('MyDB', 1);
request.onsuccess = function(event) {
const db = event.target.result;
};Web Storage的共同特点:
问题5:如何在多个浏览器标签页间共享数据?
点击查看答案
答案:
Broadcast Channel API:
// 创建广播频道
const bc = new BroadcastChannel('test_channel');
// 发送消息
bc.postMessage('Hello other tabs!');
// 接收消息
bc.onmessage = function (ev) {
console.log(ev.data);
};localStorage事件:
// 监听storage事件
window.addEventListener('storage', function(e) {
console.log('Storage changed:', e.key, e.newValue);
});
// 其他标签页修改localStorage会触发事件
localStorage.setItem('key', 'value');SharedWorker:
// main.js
const worker = new SharedWorker('worker.js');
worker.port.start();
worker.port.postMessage('Hello from main thread');
// worker.js
const connections = [];
self.onconnect = function(e) {
const port = e.ports[0];
connections.push(port);
port.onmessage = function(e) {
// 向所有连接的端口广播消息
connections.forEach(conn => conn.postMessage(e.data));
};
};问题6:GET和POST方法的区别是什么?
点击查看答案
答案:
问题7:HTTP状态码有哪些分类?请列举常用状态码。
点击查看答案
答案:
问题8:什么是跨域?有哪些解决跨域的方法?
点击查看答案
答案:
跨域定义: 当协议、域名、端口号任一不同时,即构成跨域
跨域解决方法:
CORS(跨域资源共享):
// 服务端设置响应头
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});JSONP:
// 动态创建script标签
function jsonp(url, callback) {
const script = document.createElement('script');
script.src = `${url}?callback=${callback}`;
document.head.appendChild(script);
}
// 后端返回:callback(data)代理:
// Webpack Dev Server代理
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
}
};Nginx反向代理:
server {
listen 80;
server_name localhost;
location /api/ {
proxy_pass http://backend-server/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}PostMessage:
// 发送消息
otherWindow.postMessage(message, targetOrigin);
// 接收消息
window.addEventListener('message', function(event) {
if (event.origin !== 'http://example.com') return;
console.log(event.data);
});问题9:浏览器的渲染过程是怎样的?
点击查看答案
答案: 浏览器渲染过程主要包括以下几个步骤:
性能优化建议:
问题10:重排(Reflow)和重绘(Repaint)的区别是什么?
点击查看答案
答案:
重排(Reflow):
重绘(Repaint):
区别:
优化策略:
// 避免频繁的DOM操作
// 错误示例:
for(let i = 0; i < 1000; i++) {
div.style.left = i + 'px'; // 每次都触发重排
div.style.top = i + 'px';
}
// 正确示例:
div.style.cssText = 'left: 100px; top: 100px;'; // 一次性应用
// 或者
const newLeft = 100;
const newTop = 100;
Object.assign(div.style, { left: newLeft + 'px', top: newTop + 'px' });问题11:浏览器缓存机制是怎样的?有哪些缓存策略?
点击查看答案
答案: 浏览器缓存主要分为两大类:
1. 强缓存:
Expires: HTTP/1.0时代的头部,指定过期时间(绝对时间)
Expires: Wed, 21 Oct 2025 07:28:00 GMTCache-Control: HTTP/1.1引入,优先级高于Expires
Cache-Control: max-age=3600 // 缓存1小时
Cache-Control: no-cache // 不使用强缓存,但可使用协商缓存
Cache-Control: no-store // 不缓存
Cache-Control: public // 可被任何缓存
Cache-Control: private // 仅用户浏览器可缓存2. 协商缓存:
Last-Modified / If-Modified-Since:
// 响应头
Last-Modified: Wed, 21 Oct 2025 07:28:00 GMT
// 请求头
If-Modified-Since: Wed, 21 Oct 2025 07:28:00 GMTETag / If-None-Match:
// 响应头
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
// 请求头
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"缓存策略:
问题12:WebSocket与HTTP的区别是什么?适用于什么场景?
点击查看答案
答案:
WebSocket与HTTP的区别:
特性 | HTTP | WebSocket |
|---|---|---|
连接方式 | 请求-响应模式 | 全双工通信 |
连接持久性 | 短连接,请求后关闭 | 长连接,持续通信 |
通信方式 | 客户端发起,服务器响应 | 双方可随时发送数据 |
开销 | 每次请求都包含头部信息 | 首次握手后数据帧较小 |
实时性 | 需要轮询或长轮询 | 真正实时通信 |
WebSocket实现示例:
// 客户端
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = function(event) {
console.log('连接已建立');
socket.send('Hello Server!');
};
socket.onmessage = function(event) {
console.log('收到消息:', event.data);
};
socket.onclose = function(event) {
console.log('连接已关闭');
};
// 服务端(Node.js示例)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('收到:', message);
ws.send('Echo: ' + message);
});
});适用场景:
问题13:常见的Content-Type有哪些?如何正确设置?
点击查看答案
答案:
常见Content-Type:
文本类型:
text/plain - 纯文本text/html - HTML文档text/css - CSS样式表application/json - JSON数据application/xml - XML数据text/javascript - JavaScript代码图片类型:
image/jpeg - JPEG图片image/png - PNG图片image/gif - GIF图片image/svg+xml - SVG矢量图文件类型:
application/pdf - PDF文档application/zip - ZIP压缩文件application/msword - Word文档application/vnd.ms-excel - Excel文档表单数据:
application/x-www-form-urlencoded - 传统表单数据multipart/form-data - 文件上传表单application/json - JSON数据正确设置方法:
前端设置:
// Ajax请求
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
// Axios设置
axios.post('/api/data', data, {
headers: {
'Content-Type': 'application/json'
}
});后端设置(Express示例):
app.get('/api/data', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.json({ message: 'Success' });
});
app.get('/api/file', (req, res) => {
res.setHeader('Content-Type', 'application/octet-stream');
res.download('./file.pdf');
});问题14:CSS的引入方式有哪些?有什么区别?
点击查看答案
答案:
1. 内联样式(Inline Styles):
<div style="color: red; font-size: 14px;">内联样式</div>2. 内部样式(Internal Stylesheet):
<head>
<style>
.my-class { color: red; }
</style>
</head>3. 外部样式(External Stylesheet):
<link rel="stylesheet" href="style.css">4. 导入样式(@import):
@import url('style.css');优先级(从高到低):
问题15:CSS伪类和伪元素的区别是什么?常用有哪些?
点击查看答案
答案:
伪类(Pseudo-classes):
:pseudo-class常用伪类:
a:link { color: blue; } /* 未访问的链接 */
a:visited { color: purple; } /* 已访问的链接 */
a:hover { color: red; } /* 鼠标悬停 */
a:active { color: orange; } /* 激活状态 */
a:focus { outline: 2px solid blue; } /* 获得焦点 */
input:disabled { background: #eee; } /* 禁用状态 */
input:checked + label { color: green; } /* 选中状态 */
li:first-child { font-weight: bold; } /* 第一个子元素 */
li:last-child { border-bottom: none; } /* 最后一个子元素 */
tr:nth-child(odd) { background: #f0f0f0; } /* 奇数行 */伪元素(Pseudo-elements):
::pseudo-element常用伪元素:
p::first-letter { font-size: 2em; } /* 首字母 */
p::first-line { font-weight: bold; } /* 首行 */
div::before { content: "★ "; } /* 前置内容 */
div::after { content: " ★"; } /* 后置内容 */
.quote::before { /* 引用装饰 */
content: """;
font-size: 2em;
color: #ccc;
}区别总结:
问题16:Flex布局的原理是什么?如何使用?
点击查看答案
答案:
Flex布局原理: Flex布局由弹性容器(flex container)和弹性项目(flex items)组成,通过在一维空间内调整项目的大小来填充可用空间。
容器属性:
.flex-container {
display: flex; /* 开启flex布局 */
/* 主轴方向 */
flex-direction: row | row-reverse | column | column-reverse;
/* 换行 */
flex-wrap: nowrap | wrap | wrap-reverse;
/* 主轴对齐 */
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
/* 交叉轴对齐 */
align-items: stretch | flex-start | flex-end | center | baseline;
/* 多轴对齐 */
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}项目属性:
.flex-item {
/* 放大比例 */
flex-grow: 1;
/* 缩小比例 */
flex-shrink: 1;
/* 基础大小 */
flex-basis: auto | 100px;
/* 简写 */
flex: 1; /* 相当于 flex: 1 1 0% */
/* 单个项目对齐 */
align-self: auto | flex-start | flex-end | center | baseline | stretch;
/* 排序 */
order: 0; /* 数值越小越靠前 */
}经典布局示例:
<div class="container">
<div class="header">头部</div>
<div class="main">主要内容</div>
<div class="sidebar">侧边栏</div>
<div class="footer">底部</div>
</div>.container {
display: flex;
flex-direction: column;
height: 100vh;
}
.header, .footer {
flex: 0 0 auto; /* 不放大,不缩小,根据内容确定大小 */
background: #ccc;
}
.main {
flex: 1; /* 占据剩余空间 */
display: flex;
}
.sidebar {
flex: 0 0 200px; /* 固定宽度200px */
background: #eee;
}问题17:CSS盒模型有哪几种?如何理解?