Search K
Appearance
Appearance
HTML5 API参考, Web API, DOM API, 存储API, 地理位置API, 拖拽API, 文件API, 音频视频API, Canvas API, WebSocket API
本附录提供HTML5相关API的完整参考信息,包括:
本地存储API,用于在客户端持久化存储数据。
setItem(key, value): 存储数据getItem(key): 获取数据removeItem(key): 删除数据clear(): 清空所有数据key(index): 获取指定索引的键名length: 存储项目数量// 存储数据
localStorage.setItem('username', 'John');
localStorage.setItem('settings', JSON.stringify({theme: 'dark', lang: 'zh'}));
// 获取数据
const username = localStorage.getItem('username');
const settings = JSON.parse(localStorage.getItem('settings'));
// 删除数据
localStorage.removeItem('username');
// 清空所有数据
localStorage.clear();
// 遍历所有数据
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(`${key}: ${value}`);
}
// 监听存储变化
window.addEventListener('storage', function(e) {
console.log('Storage changed:', e.key, e.oldValue, e.newValue);
});会话存储API,数据在会话结束后自动清除。
与localStorage相同
// 存储临时数据
sessionStorage.setItem('currentPage', '1');
sessionStorage.setItem('tempData', JSON.stringify({id: 123, name: 'temp'}));
// 获取临时数据
const currentPage = sessionStorage.getItem('currentPage');
const tempData = JSON.parse(sessionStorage.getItem('tempData'));
// 页面刷新后数据仍然存在
window.addEventListener('beforeunload', function() {
sessionStorage.setItem('lastActivity', Date.now());
});
window.addEventListener('load', function() {
const lastActivity = sessionStorage.getItem('lastActivity');
if (lastActivity) {
console.log('Last activity:', new Date(parseInt(lastActivity)));
}
});与localStorage相同
客户端数据库API,支持事务和索引。
// 打开数据库
const request = indexedDB.open('MyDatabase', 1);
request.onerror = function(event) {
console.error('Database error:', event.target.error);
};
request.onsuccess = function(event) {
const db = event.target.result;
console.log('Database opened successfully');
// 添加数据
addData(db, {id: 1, name: 'John', email: 'john@example.com'});
// 查询数据
getData(db, 1).then(user => {
console.log('User:', user);
});
};
request.onupgradeneeded = function(event) {
const db = event.target.result;
// 创建对象存储
const objectStore = db.createObjectStore('users', {keyPath: 'id'});
// 创建索引
objectStore.createIndex('email', 'email', {unique: true});
objectStore.createIndex('name', 'name', {unique: false});
};
// 添加数据
function addData(db, data) {
const transaction = db.transaction(['users'], 'readwrite');
const objectStore = transaction.objectStore('users');
const request = objectStore.add(data);
request.onsuccess = function() {
console.log('Data added successfully');
};
request.onerror = function() {
console.error('Error adding data');
};
}
// 查询数据
function getData(db, id) {
return new Promise((resolve, reject) => {
const transaction = db.transaction(['users'], 'readonly');
const objectStore = transaction.objectStore('users');
const request = objectStore.get(id);
request.onsuccess = function() {
resolve(request.result);
};
request.onerror = function() {
reject(request.error);
};
});
}
// 更新数据
function updateData(db, data) {
const transaction = db.transaction(['users'], 'readwrite');
const objectStore = transaction.objectStore('users');
const request = objectStore.put(data);
request.onsuccess = function() {
console.log('Data updated successfully');
};
}
// 删除数据
function deleteData(db, id) {
const transaction = db.transaction(['users'], 'readwrite');
const objectStore = transaction.objectStore('users');
const request = objectStore.delete(id);
request.onsuccess = function() {
console.log('Data deleted successfully');
};
}获取用户地理位置信息。
getCurrentPosition(): 获取当前位置watchPosition(): 监听位置变化clearWatch(): 停止监听// 检查浏览器支持
if ('geolocation' in navigator) {
console.log('Geolocation is supported');
// 获取当前位置
navigator.geolocation.getCurrentPosition(
function(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const accuracy = position.coords.accuracy;
console.log(`位置: ${latitude}, ${longitude}`);
console.log(`精度: ${accuracy} 米`);
// 在地图上显示位置
showOnMap(latitude, longitude);
},
function(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.error('用户拒绝了位置请求');
break;
case error.POSITION_UNAVAILABLE:
console.error('位置信息不可用');
break;
case error.TIMEOUT:
console.error('请求超时');
break;
default:
console.error('未知错误:', error.message);
break;
}
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 60000
}
);
// 监听位置变化
const watchId = navigator.geolocation.watchPosition(
function(position) {
console.log('位置更新:', position.coords.latitude, position.coords.longitude);
updateMap(position.coords.latitude, position.coords.longitude);
},
function(error) {
console.error('位置监听错误:', error.message);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 30000
}
);
// 停止监听
setTimeout(() => {
navigator.geolocation.clearWatch(watchId);
console.log('停止位置监听');
}, 60000);
} else {
console.log('Geolocation is not supported');
}
// 显示在地图上
function showOnMap(lat, lng) {
// 使用Google Maps或其他地图API
const map = new google.maps.Map(document.getElementById('map'), {
center: {lat: lat, lng: lng},
zoom: 15
});
const marker = new google.maps.Marker({
position: {lat: lat, lng: lng},
map: map,
title: '您的位置'
});
}
// 更新地图
function updateMap(lat, lng) {
// 更新地图中心和标记位置
map.setCenter({lat: lat, lng: lng});
marker.setPosition({lat: lat, lng: lng});
}// Position对象
position = {
coords: {
latitude: 39.9042, // 纬度
longitude: 116.4074, // 经度
accuracy: 100, // 精度(米)
altitude: null, // 海拔
altitudeAccuracy: null, // 海拔精度
heading: null, // 方向
speed: null // 速度
},
timestamp: 1234567890123 // 时间戳
};实现拖拽功能的API。
dragstart: 开始拖拽drag: 拖拽过程中dragend: 拖拽结束dragenter: 进入拖拽区域dragover: 在拖拽区域上方dragleave: 离开拖拽区域drop: 放置// HTML结构
/*
<div id="dragItem" draggable="true">可拖拽项目</div>
<div id="dropZone">放置区域</div>
*/
// 拖拽元素
const dragItem = document.getElementById('dragItem');
const dropZone = document.getElementById('dropZone');
// 拖拽开始
dragItem.addEventListener('dragstart', function(e) {
console.log('拖拽开始');
// 设置拖拽数据
e.dataTransfer.setData('text/plain', this.textContent);
e.dataTransfer.setData('text/html', this.outerHTML);
// 设置拖拽效果
e.dataTransfer.effectAllowed = 'move';
// 设置拖拽图像
const dragImage = new Image();
dragImage.src = 'drag-icon.png';
e.dataTransfer.setDragImage(dragImage, 25, 25);
// 添加样式
this.style.opacity = '0.5';
});
// 拖拽过程中
dragItem.addEventListener('drag', function(e) {
console.log('拖拽中:', e.clientX, e.clientY);
});
// 拖拽结束
dragItem.addEventListener('dragend', function(e) {
console.log('拖拽结束');
this.style.opacity = '1';
});
// 进入放置区域
dropZone.addEventListener('dragenter', function(e) {
console.log('进入放置区域');
e.preventDefault();
this.style.backgroundColor = '#e0e0e0';
});
// 在放置区域上方
dropZone.addEventListener('dragover', function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
});
// 离开放置区域
dropZone.addEventListener('dragleave', function(e) {
console.log('离开放置区域');
this.style.backgroundColor = '';
});
// 放置
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
console.log('放置');
// 获取拖拽数据
const text = e.dataTransfer.getData('text/plain');
const html = e.dataTransfer.getData('text/html');
// 处理放置
this.innerHTML = `<p>放置内容: ${text}</p>`;
this.style.backgroundColor = '';
// 获取文件(如果有)
const files = e.dataTransfer.files;
if (files.length > 0) {
handleFiles(files);
}
});
// 处理文件拖拽
function handleFiles(files) {
Array.from(files).forEach(file => {
console.log('文件:', file.name, file.type, file.size);
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
img.style.maxWidth = '200px';
dropZone.appendChild(img);
};
reader.readAsDataURL(file);
}
});
}
// 文件拖拽增强
dropZone.addEventListener('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
// 检查是否包含文件
const hasFiles = Array.from(e.dataTransfer.types).includes('Files');
if (hasFiles) {
e.dataTransfer.dropEffect = 'copy';
this.classList.add('drag-over');
}
});
dropZone.addEventListener('dragleave', function(e) {
this.classList.remove('drag-over');
});// DataTransfer对象属性和方法
const dataTransfer = {
// 属性
dropEffect: 'move', // 拖拽效果
effectAllowed: 'all', // 允许的效果
files: FileList, // 文件列表
types: ['text/plain'], // 数据类型
// 方法
setData: function(type, data) {}, // 设置数据
getData: function(type) {}, // 获取数据
clearData: function(type) {}, // 清除数据
setDragImage: function(img, x, y) {} // 设置拖拽图像
};处理文件上传和读取的API。
File: 文件对象FileList: 文件列表FileReader: 文件读取器Blob: 二进制对象// HTML: <input type="file" id="fileInput" multiple>
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
const files = e.target.files;
// 处理每个文件
Array.from(files).forEach(file => {
processFile(file);
});
});
// 处理文件
function processFile(file) {
console.log('文件信息:');
console.log('名称:', file.name);
console.log('大小:', file.size, 'bytes');
console.log('类型:', file.type);
console.log('最后修改:', new Date(file.lastModified));
// 根据文件类型处理
if (file.type.startsWith('image/')) {
readImageFile(file);
} else if (file.type.startsWith('text/')) {
readTextFile(file);
} else {
readBinaryFile(file);
}
}
// 读取图像文件
function readImageFile(file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
img.style.maxWidth = '300px';
document.body.appendChild(img);
};
reader.readAsDataURL(file);
}
// 读取文本文件
function readTextFile(file) {
const reader = new FileReader();
reader.onload = function(e) {
const pre = document.createElement('pre');
pre.textContent = e.target.result;
document.body.appendChild(pre);
};
reader.readAsText(file, 'UTF-8');
}
// 读取二进制文件
function readBinaryFile(file) {
const reader = new FileReader();
reader.onload = function(e) {
const arrayBuffer = e.target.result;
const uint8Array = new Uint8Array(arrayBuffer);
console.log('二进制数据:', uint8Array);
// 创建Blob
const blob = new Blob([uint8Array], {type: file.type});
console.log('Blob:', blob);
};
reader.readAsArrayBuffer(file);
}
// 文件读取进度
function readFileWithProgress(file) {
const reader = new FileReader();
reader.onloadstart = function() {
console.log('开始读取');
};
reader.onprogress = function(e) {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
console.log(`读取进度: ${percentComplete.toFixed(2)}%`);
}
};
reader.onload = function(e) {
console.log('读取完成');
console.log('结果:', e.target.result);
};
reader.onerror = function() {
console.error('读取错误');
};
reader.readAsText(file);
}
// 创建和下载文件
function createAndDownloadFile() {
const content = 'Hello, World!\n这是一个测试文件。';
const blob = new Blob([content], {type: 'text/plain'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'test.txt';
a.click();
// 释放URL
URL.revokeObjectURL(url);
}
// 文件分片上传
function uploadFileInChunks(file, chunkSize = 1024 * 1024) {
const totalChunks = Math.ceil(file.size / chunkSize);
for (let i = 0; i < totalChunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);
uploadChunk(chunk, i, totalChunks);
}
}
function uploadChunk(chunk, index, total) {
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('index', index);
formData.append('total', total);
fetch('/upload-chunk', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(`分片 ${index + 1}/${total} 上传完成`);
})
.catch(error => {
console.error('上传错误:', error);
});
}控制音频和视频播放的API。
currentTime: 当前播放时间duration: 总时长paused: 是否暂停volume: 音量playbackRate: 播放速度play(): 播放pause(): 暂停load(): 重新加载// HTML: <video id="myVideo" controls></video>
const video = document.getElementById('myVideo');
// 基本控制
function playVideo() {
video.play().then(() => {
console.log('视频开始播放');
}).catch(error => {
console.error('播放失败:', error);
});
}
function pauseVideo() {
video.pause();
console.log('视频暂停');
}
// 设置音量
function setVolume(volume) {
video.volume = Math.max(0, Math.min(1, volume));
console.log('音量设置为:', video.volume);
}
// 设置播放速度
function setPlaybackRate(rate) {
video.playbackRate = rate;
console.log('播放速度设置为:', rate);
}
// 跳转到指定时间
function seekTo(seconds) {
video.currentTime = seconds;
console.log('跳转到:', seconds, '秒');
}
// 事件监听
video.addEventListener('loadstart', () => {
console.log('开始加载');
});
video.addEventListener('loadedmetadata', () => {
console.log('元数据加载完成');
console.log('视频时长:', video.duration, '秒');
console.log('视频尺寸:', video.videoWidth, 'x', video.videoHeight);
});
video.addEventListener('loadeddata', () => {
console.log('数据加载完成');
});
video.addEventListener('canplay', () => {
console.log('可以播放');
});
video.addEventListener('canplaythrough', () => {
console.log('可以流畅播放');
});
video.addEventListener('play', () => {
console.log('开始播放');
});
video.addEventListener('pause', () => {
console.log('暂停播放');
});
video.addEventListener('ended', () => {
console.log('播放结束');
});
video.addEventListener('timeupdate', () => {
const progress = (video.currentTime / video.duration) * 100;
console.log('播放进度:', progress.toFixed(2), '%');
updateProgressBar(progress);
});
video.addEventListener('volumechange', () => {
console.log('音量变化:', video.volume);
});
video.addEventListener('ratechange', () => {
console.log('播放速度变化:', video.playbackRate);
});
video.addEventListener('error', (e) => {
console.error('播放错误:', e);
});
// 更新进度条
function updateProgressBar(progress) {
const progressBar = document.getElementById('progressBar');
if (progressBar) {
progressBar.style.width = progress + '%';
}
}
// 自定义播放器控制
class VideoPlayer {
constructor(videoElement) {
this.video = videoElement;
this.setupEventListeners();
}
setupEventListeners() {
this.video.addEventListener('loadedmetadata', () => {
this.updateDuration();
});
this.video.addEventListener('timeupdate', () => {
this.updateProgress();
});
}
play() {
return this.video.play();
}
pause() {
this.video.pause();
}
togglePlay() {
if (this.video.paused) {
this.play();
} else {
this.pause();
}
}
setVolume(volume) {
this.video.volume = Math.max(0, Math.min(1, volume));
}
seek(seconds) {
this.video.currentTime = seconds;
}
seekByPercentage(percentage) {
this.video.currentTime = (percentage / 100) * this.video.duration;
}
updateDuration() {
const duration = this.formatTime(this.video.duration);
document.getElementById('duration').textContent = duration;
}
updateProgress() {
const current = this.formatTime(this.video.currentTime);
const progress = (this.video.currentTime / this.video.duration) * 100;
document.getElementById('currentTime').textContent = current;
document.getElementById('progressBar').style.width = progress + '%';
}
formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = Math.floor(seconds % 60);
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}
}
// 使用自定义播放器
const player = new VideoPlayer(video);高级音频处理API。
// 创建音频上下文
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// 加载音频文件
async function loadAudioFile(url) {
try {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
return audioBuffer;
} catch (error) {
console.error('加载音频文件失败:', error);
}
}
// 播放音频
function playAudio(audioBuffer) {
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start();
}
// 音频效果处理
function createAudioEffect() {
// 创建增益节点
const gainNode = audioContext.createGain();
gainNode.gain.value = 0.5;
// 创建滤波器
const filterNode = audioContext.createBiquadFilter();
filterNode.type = 'lowpass';
filterNode.frequency.value = 1000;
// 连接节点
source.connect(filterNode);
filterNode.connect(gainNode);
gainNode.connect(audioContext.destination);
}
// 生成音调
function generateTone(frequency, duration) {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.frequency.value = frequency;
oscillator.type = 'sine';
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + duration);
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + duration);
}
// 使用示例
loadAudioFile('audio.mp3').then(audioBuffer => {
playAudio(audioBuffer);
});
// 生成440Hz的音调,持续1秒
generateTone(440, 1);2D图形绘制API。
getContext('2d'): 获取2D绘图上下文fillRect(): 填充矩形strokeRect(): 描边矩形clearRect(): 清除矩形beginPath(): 开始路径moveTo(): 移动到lineTo(): 画线到arc(): 画圆弧fill(): 填充stroke(): 描边// HTML: <canvas id="myCanvas" width="800" height="600"></canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 基本绘制
function drawBasicShapes() {
// 填充矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
// 描边矩形
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.strokeRect(130, 10, 100, 100);
// 清除矩形
ctx.clearRect(50, 50, 20, 20);
}
// 绘制路径
function drawPaths() {
// 绘制线条
ctx.beginPath();
ctx.moveTo(10, 150);
ctx.lineTo(100, 150);
ctx.lineTo(100, 200);
ctx.strokeStyle = 'green';
ctx.lineWidth = 3;
ctx.stroke();
// 绘制圆形
ctx.beginPath();
ctx.arc(200, 175, 25, 0, 2 * Math.PI);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.strokeStyle = 'orange';
ctx.lineWidth = 2;
ctx.stroke();
}
// 绘制文本
function drawText() {
ctx.font = '20px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas!', 10, 250);
ctx.font = '16px serif';
ctx.strokeStyle = 'red';
ctx.strokeText('Stroked Text', 10, 280);
}
// 绘制图像
function drawImage() {
const img = new Image();
img.onload = function() {
// 绘制完整图像
ctx.drawImage(img, 300, 10);
// 绘制缩放图像
ctx.drawImage(img, 300, 150, 100, 100);
// 绘制图像的一部分
ctx.drawImage(img, 50, 50, 100, 100, 300, 280, 150, 150);
};
img.src = 'image.jpg';
}
// 变换
function applyTransforms() {
ctx.save(); // 保存当前状态
// 平移
ctx.translate(500, 100);
// 旋转
ctx.rotate(Math.PI / 4);
// 缩放
ctx.scale(1.5, 1.5);
// 绘制变换后的图形
ctx.fillStyle = 'purple';
ctx.fillRect(0, 0, 50, 50);
ctx.restore(); // 恢复状态
}
// 渐变
function createGradient() {
// 线性渐变
const linearGradient = ctx.createLinearGradient(0, 0, 200, 0);
linearGradient.addColorStop(0, 'red');
linearGradient.addColorStop(0.5, 'yellow');
linearGradient.addColorStop(1, 'blue');
ctx.fillStyle = linearGradient;
ctx.fillRect(10, 320, 200, 50);
// 径向渐变
const radialGradient = ctx.createRadialGradient(125, 425, 0, 125, 425, 50);
radialGradient.addColorStop(0, 'white');
radialGradient.addColorStop(1, 'black');
ctx.fillStyle = radialGradient;
ctx.fillRect(75, 375, 100, 100);
}
// 动画
function animate() {
let x = 0;
let y = 300;
let dx = 2;
let dy = 1;
const radius = 20;
function draw() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制球
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
// 更新位置
x += dx;
y += dy;
// 边界检测
if (x + radius > canvas.width || x - radius < 0) {
dx = -dx;
}
if (y + radius > canvas.height || y - radius < 0) {
dy = -dy;
}
requestAnimationFrame(draw);
}
draw();
}
// 交互
function setupInteraction() {
canvas.addEventListener('mousemove', function(e) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制跟随鼠标的圆
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
});
canvas.addEventListener('click', function(e) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// 在点击位置绘制圆
ctx.beginPath();
ctx.arc(x, y, 15, 0, 2 * Math.PI);
ctx.fillStyle = 'green';
ctx.fill();
});
}
// 执行绘制
drawBasicShapes();
drawPaths();
drawText();
drawImage();
applyTransforms();
createGradient();
animate();
setupInteraction();实时双向通信API。
// 创建WebSocket连接
const ws = new WebSocket('ws://localhost:8080');
// 连接打开
ws.onopen = function(event) {
console.log('WebSocket连接已打开');
// 发送消息
ws.send('Hello Server!');
// 发送JSON数据
ws.send(JSON.stringify({
type: 'greeting',
message: 'Hello from client',
timestamp: Date.now()
}));
};
// 接收消息
ws.onmessage = function(event) {
console.log('收到消息:', event.data);
try {
const data = JSON.parse(event.data);
handleMessage(data);
} catch (e) {
console.log('收到文本消息:', event.data);
}
};
// 处理消息
function handleMessage(data) {
switch (data.type) {
case 'greeting':
console.log('收到问候:', data.message);
break;
case 'notification':
showNotification(data.message);
break;
case 'update':
updateUI(data.data);
break;
default:
console.log('未知消息类型:', data);
}
}
// 连接关闭
ws.onclose = function(event) {
console.log('WebSocket连接已关闭');
console.log('关闭代码:', event.code);
console.log('关闭原因:', event.reason);
// 重连逻辑
setTimeout(() => {
reconnect();
}, 5000);
};
// 连接错误
ws.onerror = function(error) {
console.error('WebSocket错误:', error);
};
// 发送消息函数
function sendMessage(type, data) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: type,
data: data,
timestamp: Date.now()
}));
} else {
console.warn('WebSocket连接未打开');
}
}
// 重连函数
function reconnect() {
console.log('尝试重新连接...');
// 重新创建WebSocket连接
ws = new WebSocket('ws://localhost:8080');
// 重新绑定事件处理器
// ...
}
// 心跳检测
function startHeartbeat() {
setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({type: 'ping'}));
}
}, 30000); // 每30秒发送一次心跳
}
// 聊天应用示例
class ChatApp {
constructor(wsUrl) {
this.ws = new WebSocket(wsUrl);
this.setupEventListeners();
}
setupEventListeners() {
this.ws.onopen = () => {
console.log('聊天连接已建立');
this.updateStatus('已连接');
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
this.handleMessage(data);
};
this.ws.onclose = () => {
console.log('聊天连接已断开');
this.updateStatus('已断开');
};
this.ws.onerror = (error) => {
console.error('聊天连接错误:', error);
this.updateStatus('连接错误');
};
}
handleMessage(data) {
switch (data.type) {
case 'message':
this.displayMessage(data.user, data.message);
break;
case 'userJoined':
this.displaySystemMessage(`${data.user} 加入了聊天`);
break;
case 'userLeft':
this.displaySystemMessage(`${data.user} 离开了聊天`);
break;
}
}
sendMessage(message) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({
type: 'message',
message: message,
timestamp: Date.now()
}));
}
}
displayMessage(user, message) {
const chatContainer = document.getElementById('chatContainer');
const messageElement = document.createElement('div');
messageElement.innerHTML = `<strong>${user}:</strong> ${message}`;
chatContainer.appendChild(messageElement);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
displaySystemMessage(message) {
const chatContainer = document.getElementById('chatContainer');
const messageElement = document.createElement('div');
messageElement.innerHTML = `<em>${message}</em>`;
messageElement.style.color = 'gray';
chatContainer.appendChild(messageElement);
}
updateStatus(status) {
const statusElement = document.getElementById('status');
if (statusElement) {
statusElement.textContent = status;
}
}
}
// 使用聊天应用
const chat = new ChatApp('ws://localhost:8080');服务器推送事件API。
// 创建EventSource连接
const eventSource = new EventSource('/events');
// 监听消息
eventSource.onmessage = function(event) {
console.log('收到消息:', event.data);
try {
const data = JSON.parse(event.data);
handleServerMessage(data);
} catch (e) {
console.log('收到文本消息:', event.data);
}
};
// 监听特定事件
eventSource.addEventListener('notification', function(event) {
console.log('收到通知:', event.data);
showNotification(event.data);
});
eventSource.addEventListener('update', function(event) {
console.log('收到更新:', event.data);
const data = JSON.parse(event.data);
updateUI(data);
});
// 连接打开
eventSource.onopen = function() {
console.log('SSE连接已打开');
};
// 连接错误
eventSource.onerror = function(error) {
console.error('SSE错误:', error);
if (eventSource.readyState === EventSource.CLOSED) {
console.log('SSE连接已关闭');
}
};
// 处理服务器消息
function handleServerMessage(data) {
switch (data.type) {
case 'status':
updateStatus(data.message);
break;
case 'data':
updateData(data.payload);
break;
case 'alert':
showAlert(data.message);
break;
default:
console.log('未知消息类型:', data);
}
}
// 实时数据监控示例
class RealtimeMonitor {
constructor() {
this.eventSource = new EventSource('/api/monitor');
this.setupEventListeners();
}
setupEventListeners() {
this.eventSource.addEventListener('metrics', (event) => {
const metrics = JSON.parse(event.data);
this.updateMetrics(metrics);
});
this.eventSource.addEventListener('alert', (event) => {
const alert = JSON.parse(event.data);
this.showAlert(alert);
});
}
updateMetrics(metrics) {
document.getElementById('cpu').textContent = metrics.cpu + '%';
document.getElementById('memory').textContent = metrics.memory + '%';
document.getElementById('disk').textContent = metrics.disk + '%';
}
showAlert(alert) {
const alertContainer = document.getElementById('alerts');
const alertElement = document.createElement('div');
alertElement.className = `alert alert-${alert.level}`;
alertElement.textContent = alert.message;
alertContainer.appendChild(alertElement);
// 自动移除警告
setTimeout(() => {
alertContainer.removeChild(alertElement);
}, 5000);
}
close() {
this.eventSource.close();
}
}
// 使用实时监控
const monitor = new RealtimeMonitor();操作浏览器历史记录的API。
// 添加历史记录
history.pushState({page: 1}, 'Title 1', '/page1');
history.pushState({page: 2}, 'Title 2', '/page2');
// 替换当前历史记录
history.replaceState({page: 2, updated: true}, 'Title 2 Updated', '/page2');
// 监听历史记录变化
window.addEventListener('popstate', function(event) {
console.log('历史记录变化:', event.state);
if (event.state) {
loadPage(event.state.page);
}
});
// 导航
function navigateToPage(page) {
history.pushState({page: page}, `Page ${page}`, `/page${page}`);
loadPage(page);
}
// 加载页面
function loadPage(page) {
// 模拟页面加载
console.log(`加载页面 ${page}`);
document.getElementById('content').innerHTML = `<h1>Page ${page}</h1>`;
}
// 单页应用路由示例
class SimpleRouter {
constructor() {
this.routes = {};
this.setupEventListeners();
}
addRoute(path, handler) {
this.routes[path] = handler;
}
navigate(path, state = {}) {
if (this.routes[path]) {
history.pushState(state, '', path);
this.routes[path](state);
}
}
setupEventListeners() {
window.addEventListener('popstate', (event) => {
const path = window.location.pathname;
if (this.routes[path]) {
this.routes[path](event.state || {});
}
});
}
}
// 使用路由
const router = new SimpleRouter();
router.addRoute('/home', () => {
document.getElementById('app').innerHTML = '<h1>首页</h1>';
});
router.addRoute('/about', () => {
document.getElementById('app').innerHTML = '<h1>关于我们</h1>';
});桌面通知API。
// 检查通知权限
function checkNotificationPermission() {
console.log('通知权限:', Notification.permission);
if (Notification.permission === 'default') {
Notification.requestPermission().then(permission => {
console.log('权限请求结果:', permission);
});
}
}
// 发送通知
function sendNotification(title, options = {}) {
if (Notification.permission === 'granted') {
const notification = new Notification(title, {
body: options.body || '',
icon: options.icon || '/icon.png',
badge: options.badge || '/badge.png',
image: options.image || '',
tag: options.tag || 'default',
timestamp: Date.now(),
requireInteraction: options.requireInteraction || false,
silent: options.silent || false,
...options
});
// 通知事件
notification.onclick = function(event) {
console.log('通知被点击');
window.focus();
notification.close();
};
notification.onclose = function() {
console.log('通知已关闭');
};
notification.onerror = function(error) {
console.error('通知错误:', error);
};
// 自动关闭
setTimeout(() => {
notification.close();
}, 5000);
return notification;
} else {
console.warn('通知权限未授予');
}
}
// 使用示例
checkNotificationPermission();
// 发送简单通知
sendNotification('新消息', {
body: '您有一条新消息',
icon: '/message-icon.png'
});
// 发送复杂通知
sendNotification('系统更新', {
body: '系统将在5分钟后重启',
icon: '/system-icon.png',
badge: '/update-badge.png',
tag: 'system-update',
requireInteraction: true,
actions: [
{
action: 'postpone',
title: '推迟',
icon: '/postpone-icon.png'
},
{
action: 'restart',
title: '立即重启',
icon: '/restart-icon.png'
}
]
});后台线程API,用于并行处理任务。
// 主线程代码
if (typeof Worker !== 'undefined') {
// 创建Worker
const worker = new Worker('worker.js');
// 发送消息给Worker
worker.postMessage({
command: 'start',
data: [1, 2, 3, 4, 5]
});
// 接收Worker消息
worker.onmessage = function(event) {
console.log('Worker返回:', event.data);
if (event.data.type === 'result') {
document.getElementById('result').textContent = event.data.value;
} else if (event.data.type === 'progress') {
updateProgress(event.data.value);
}
};
// Worker错误处理
worker.onerror = function(error) {
console.error('Worker错误:', error);
};
// 终止Worker
setTimeout(() => {
worker.terminate();
console.log('Worker已终止');
}, 10000);
} else {
console.log('浏览器不支持Web Workers');
}
// worker.js文件内容
/*
self.onmessage = function(event) {
const { command, data } = event.data;
if (command === 'start') {
// 执行计算密集型任务
const result = processData(data);
// 发送结果回主线程
self.postMessage({
type: 'result',
value: result
});
}
};
function processData(data) {
let sum = 0;
const total = data.length;
for (let i = 0; i < total; i++) {
// 模拟复杂计算
for (let j = 0; j < 1000000; j++) {
sum += data[i] * Math.sqrt(j);
}
// 发送进度更新
self.postMessage({
type: 'progress',
value: (i + 1) / total * 100
});
}
return sum;
}
*/
// 更复杂的Worker使用示例
class WorkerManager {
constructor() {
this.workers = [];
this.taskQueue = [];
this.maxWorkers = navigator.hardwareConcurrency || 4;
}
addTask(task) {
return new Promise((resolve, reject) => {
this.taskQueue.push({
task: task,
resolve: resolve,
reject: reject
});
this.processQueue();
});
}
processQueue() {
if (this.taskQueue.length === 0) return;
const availableWorker = this.getAvailableWorker();
if (availableWorker) {
const { task, resolve, reject } = this.taskQueue.shift();
this.executeTask(availableWorker, task, resolve, reject);
}
}
getAvailableWorker() {
let worker = this.workers.find(w => !w.busy);
if (!worker && this.workers.length < this.maxWorkers) {
worker = this.createWorker();
this.workers.push(worker);
}
return worker;
}
createWorker() {
const worker = new Worker('worker.js');
worker.busy = false;
worker.onmessage = (event) => {
if (worker.currentResolve) {
worker.currentResolve(event.data);
worker.currentResolve = null;
worker.busy = false;
this.processQueue();
}
};
worker.onerror = (error) => {
if (worker.currentReject) {
worker.currentReject(error);
worker.currentReject = null;
worker.busy = false;
this.processQueue();
}
};
return worker;
}
executeTask(worker, task, resolve, reject) {
worker.busy = true;
worker.currentResolve = resolve;
worker.currentReject = reject;
worker.postMessage(task);
}
terminateAll() {
this.workers.forEach(worker => {
worker.terminate();
});
this.workers = [];
this.taskQueue = [];
}
}
// 使用Worker管理器
const workerManager = new WorkerManager();
// 添加任务
workerManager.addTask({
command: 'calculate',
data: [1, 2, 3, 4, 5]
}).then(result => {
console.log('计算结果:', result);
});
workerManager.addTask({
command: 'process',
data: 'some data'
}).then(result => {
console.log('处理结果:', result);
});本参考手册涵盖了HTML5的主要API,包括:
每个API都提供了详细的使用示例、浏览器兼容性信息和最佳实践建议,帮助开发者快速掌握和应用这些现代Web技术。
本文档是HTML5学习小册的一部分,更多内容请查看其他章节。