1、栈和堆内存可视化演示页面
(1)页面效果

(2)代码演示
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>栈和堆内存可视化演示</title><script src="https://cdn.tailwindcss.com"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet"><script>tailwind.config = {theme: {extend: {colors: {primary: '#3B82F6',secondary: '#10B981',accent: '#F59E0B',dark: '#1E293B',light: '#F8FAFC'},fontFamily: {inter: ['Inter', 'sans-serif'],},}}}</script><style type="text/tailwindcss">@layer utilities {.content-auto {content-visibility: auto;}.memory-block {@apply transition-all duration-300 ease-in-out transform hover:scale-105;}.stack-block {@apply bg-secondary text-white memory-block;}.heap-block {@apply bg-primary text-white memory-block;}.btn-primary {@apply bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg shadow transition-all duration-200 transform hover:scale-105 active:scale-95;}.btn-secondary {@apply bg-secondary hover:bg-secondary/90 text-white font-medium py-2 px-4 rounded-lg shadow transition-all duration-200 transform hover:scale-105 active:scale-95;}.memory-container {@apply border-2 border-dark rounded-lg shadow-lg p-4 h-[400px] overflow-y-auto;}}</style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen flex flex-col"><header class="bg-gradient-to-r from-primary to-secondary text-white shadow-lg"><div class="container mx-auto px-4 py-6"><h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold flex items-center justify-center"><i class="fa-solid fa-microchip mr-3"></i>栈和堆内存可视化演示</h1><p class="text-center mt-2 opacity-90 text-[clamp(1rem,2vw,1.2rem)]">探索计算机内存的工作原理</p></div></header><main class="flex-grow container mx-auto px-4 py-8"><div class="max-w-6xl mx-auto"><div class="bg-white rounded-xl shadow-xl p-6 mb-8"><div class="flex flex-col md:flex-row gap-8"><div class="md:w-1/2"><h2 class="text-xl font-bold mb-4 flex items-center"><i class="fa-solid fa-stack-overflow text-secondary mr-2"></i>栈内存</h2><div class="memory-container bg-gray-50" id="stack-container"><div class="flex justify-center items-center h-full text-gray-500" id="stack-placeholder"><i class="fa-solid fa-box-open mr-2"></i>栈为空</div></div><div class="mt-4 flex justify-center gap-3"><button id="push-stack" class="btn-secondary"><i class="fa-solid fa-plus mr-1"></i>压栈</button><button id="pop-stack" class="btn-secondary"><i class="fa-solid fa-minus mr-1"></i>弹栈</button></div></div><div class="md:w-1/2"><h2 class="text-xl font-bold mb-4 flex items-center"><i class="fa-solid fa-database text-primary mr-2"></i>堆内存</h2><div class="memory-container bg-gray-50" id="heap-container"><div class="flex justify-center items-center h-full text-gray-500" id="heap-placeholder"><i class="fa-solid fa-box-open mr-2"></i>堆为空</div></div><div class="mt-4 flex justify-center gap-3"><button id="allocate-heap" class="btn-primary"><i class="fa-solid fa-plus mr-1"></i>分配堆</button><button id="deallocate-heap" class="btn-primary"><i class="fa-solid fa-minus mr-1"></i>释放堆</button></div></div></div></div><div class="bg-white rounded-xl shadow-xl p-6 mb-8"><h2 class="text-xl font-bold mb-4">内存工作原理</h2><div class="grid grid-cols-1 md:grid-cols-2 gap-6"><div class="bg-blue-50 p-4 rounded-lg border-l-4 border-primary"><h3 class="font-bold text-primary mb-2">栈内存特点</h3><ul class="list-disc pl-5 space-y-2"><li>后进先出(LIFO)结构</li><li>存储局部变量和函数调用信息</li><li>由系统自动管理,速度快</li><li>空间连续,内存碎片少</li><li>大小固定,超出会导致栈溢出</li></ul></div><div class="bg-green-50 p-4 rounded-lg border-l-4 border-secondary"><h3 class="font-bold text-secondary mb-2">堆内存特点</h3><ul class="list-disc pl-5 space-y-2"><li>动态分配内存空间</li><li>存储对象和数组等引用类型</li><li>需要手动管理(通过垃圾回收)</li><li>空间不连续,可能产生内存碎片</li><li>大小灵活,但分配和回收开销大</li></ul></div></div></div></div></main><footer class="bg-dark text-white py-6"><div class="container mx-auto px-4 text-center"><p>栈和堆内存可视化演示 © 2025</p><p class="text-sm mt-2 opacity-70">探索计算机内存的工作原理</p></div></footer><script>// 数据模型let stack = [];let heap = [];// DOM 元素const stackContainer = document.getElementById('stack-container');const heapContainer = document.getElementById('heap-container');const stackPlaceholder = document.getElementById('stack-placeholder');const heapPlaceholder = document.getElementById('heap-placeholder');const pushStackBtn = document.getElementById('push-stack');const popStackBtn = document.getElementById('pop-stack');const allocateHeapBtn = document.getElementById('allocate-heap');const deallocateHeapBtn = document.getElementById('deallocate-heap');// 栈操作function pushStack() {const value = Math.floor(Math.random() * 1000);stack.push(value);updateStackDisplay();// 添加动画效果const newElement = stackContainer.querySelector('.stack-block:last-child');if (newElement) {newElement.classList.add('scale-110');setTimeout(() => {newElement.classList.remove('scale-110');}, 300);}}function popStack() {if (stack.length === 0) {showToast('栈已为空!', 'error');return;}const removedValue = stack.pop();updateStackDisplay();showToast(`弹出栈: ${removedValue}`, 'success');}// 堆操作function allocateHeap() {const size = Math.floor(Math.random() * 3) + 1; // 1-3个单元const value = Math.floor(Math.random() * 1000);const memoryBlock = { id: Date.now(), size, value };heap.push(memoryBlock);updateHeapDisplay();// 添加动画效果const newElements = heapContainer.querySelectorAll(`[data-id="${memoryBlock.id}"]`);newElements.forEach(el => {el.classList.add('scale-110');setTimeout(() => {el.classList.remove('scale-110');}, 300);});}function deallocateHeap() {if (heap.length === 0) {showToast('堆已为空!', 'error');return;}// 随机选择一个内存块释放const randomIndex = Math.floor(Math.random() * heap.length);const removedBlock = heap.splice(randomIndex, 1)[0];updateHeapDisplay();showToast(`释放堆内存块: ${removedBlock.value} (大小: ${removedBlock.size})`, 'success');}// 更新栈显示function updateStackDisplay() {stackContainer.innerHTML = '';if (stack.length === 0) {stackContainer.appendChild(stackPlaceholder);return;}stackPlaceholder.remove();// 从栈顶到栈底显示元素(最新的在顶部)for (let i = stack.length - 1; i >= 0; i--) {const value = stack[i];const div = document.createElement('div');div.className = 'stack-block rounded-md py-2 px-3 mb-1 flex justify-between items-center';div.innerHTML = `<span>${value}</span><span class="text-xs opacity-70">地址: 0x${(1000 + i).toString(16).toUpperCase()}</span>`;stackContainer.appendChild(div);}}// 更新堆显示function updateHeapDisplay() {heapContainer.innerHTML = '';if (heap.length === 0) {heapContainer.appendChild(heapPlaceholder);return;}heapPlaceholder.remove();let address = 2000; // 起始地址// 显示所有内存块heap.forEach(block => {const blockGroup = document.createElement('div');blockGroup.className = 'mb-2';// 每个内存块可能占据多个单元for (let i = 0; i < block.size; i++) {const div = document.createElement('div');div.className = 'heap-block rounded-md py-2 px-3 mb-1 flex justify-between items-center';div.dataset.id = block.id;if (i === 0) {// 内存块的第一个单元显示完整信息div.innerHTML = `<span>${block.value}</span><div class="text-xs opacity-70"><span>地址: 0x${address.toString(16).toUpperCase()}</span><span class="ml-2">大小: ${block.size} 单元</span></div>`;} else {// 后续单元只显示地址div.innerHTML = `<span>...</span><span class="text-xs opacity-70">地址: 0x${address.toString(16).toUpperCase()}</span>`;}blockGroup.appendChild(div);address++;}heapContainer.appendChild(blockGroup);});}// 显示提示消息function showToast(message, type = 'info') {const toast = document.createElement('div');toast.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 transform transition-all duration-500 ease-in-out translate-x-full ${type === 'success' ? 'bg-green-500 text-white' : type === 'error' ? 'bg-red-500 text-white' : 'bg-blue-500 text-white'}`;toast.innerHTML = `<div class="flex items-center"><i class="fa-solid ${type === 'success' ? 'fa-check-circle mr-2' : type === 'error' ? 'fa-exclamation-circle mr-2' : 'fa-info-circle mr-2'}"></i><span>${message}</span></div>`;document.body.appendChild(toast);// 显示动画setTimeout(() => {toast.classList.remove('translate-x-full');toast.classList.add('translate-x-0');}, 10);// 自动关闭setTimeout(() => {toast.classList.remove('translate-x-0');toast.classList.add('translate-x-full');setTimeout(() => {document.body.removeChild(toast);}, 500);}, 3000);}// 事件监听pushStackBtn.addEventListener('click', pushStack);popStackBtn.addEventListener('click', popStack);allocateHeapBtn.addEventListener('click', allocateHeap);deallocateHeapBtn.addEventListener('click', deallocateHeap);// 初始化显示updateStackDisplay();updateHeapDisplay();</script>
</body>
</html>