<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>轻量级货架货物管理系统</title>
<!-- 主题色变量 -->
<style>
:root {
--color-bg-main: rgba(173,216,230,0.2);
--color-primary: #a1c4fd;
--color-silver-gray: #bbbfc4;
--color-white-gradient-start: #fafafa;
--color-white-gradient-end: #ffffff;
--sidebar-width-expanded: 280px;
--sidebar-width-collapsed: 56px;
--transition-time: 0.3s;
--font-family: "PingFang SC","Microsoft Yahei",Arial,sans-serif;
}
* {
box-sizing: border-box;
}
body,html {
margin:0; padding:0; height:100%;
font-family: var(--font-family);
background: var(--color-white-gradient-start);
color:#222;
user-select:none;
overflow: hidden;
}
#container {
height: 100vh;
display: flex;
background: linear-gradient(to bottom, var(--color-white-gradient-start), var(--color-white-gradient-end));
position: relative;
}
/* 左侧边栏 */
#sidebar {
width: var(--sidebar-width-expanded);
background: rgba(173,216,230,0.35);
backdrop-filter: blur(4px);
box-shadow: inset -2px 0 6px rgba(0,0,0,0.06);
display: flex;
flex-direction: column;
transition: width var(--transition-time) ease;
overflow: hidden;
}
#sidebar.collapsed {
width: var(--sidebar-width-collapsed);
}
#sidebar header {
height: 60px;
display: flex;
align-items: center;
padding: 0 12px;
border-bottom: 1px solid var(--color-silver-gray);
}
#sidebar header img.logo {
height: 40px;
width: 40px;
border-radius: 6px;
cursor: pointer;
object-fit: contain;
}
#sidebar header .title {
margin-left: 12px;
font-size: 1.25rem;
font-weight: 600;
white-space: nowrap;
color: #145eaa;
user-select: text;
}
#sidebar.collapsed header .title {
display: none;
}
#uploadLogoBtn {
display: none;
}
#sidebar.collapsed #uploadLogoLabel {
display: none;
}
#uploadLogoLabel {
cursor: pointer;
margin-left: 8px;
color: var(--color-primary);
font-size: 0.85rem;
}
/* 货架列表容器 */
#shelfList {
flex: 1;
overflow-y: auto;
margin-top: 8px;
padding: 4px 8px;
}
#shelfList ul {
list-style:none;
padding: 0; margin:0;
}
#shelfList li {
display: flex;
align-items: center;
padding: 8px 12px;
margin: 4px 0;
background: rgba(255 255 255 / 0.6);
border-radius: 6px;
cursor: pointer;
user-select:none;
transition: background 0.2s;
}
#shelfList li.selected {
background: var(--color-primary);
color: white;
}
#shelfList li.collapsed-tooltip {
position: relative;
}
#shelfList li.collapsed-tooltip:hover::after {
content: attr(data-name);
position: absolute;
left: 60px;
top: 50%;
transform: translateY(-50%);
background: #222222c0;
color: #fff;
font-size: 0.85rem;
padding: 3px 10px;
border-radius: 6px;
white-space: nowrap;
pointer-events:none;
z-index: 20;
}
#shelfList li input.rename {
flex-grow: 1;
font-size: 1rem;
border:none;
border-radius: 4px;
padding: 4px 6px;
outline:none;
}
#shelfList li button.deleteShelf {
margin-left: auto;
border: none;
background: #e04e4e;
color: white;
border-radius: 4px;
padding: 4px 6px;
cursor: pointer;
font-weight: 700;
user-select:none;
}
#shelfList li button.deleteShelf:disabled {
background: #ccc;
cursor: not-allowed;
}
#addShelfBtn {
margin: 8px 12px;
padding: 6px 12px;
background: var(--color-primary);
color: #fff;
border:none;
border-radius: 6px;
cursor:pointer;
font-size: 1rem;
user-select:none;
transition: background 0.2s;
}
#addShelfBtn:hover {
background: #7bb1fc;
}
/* 底部折叠按钮 */
#sidebarFooter {
height: 48px;
border-top: 1px solid var(--color-silver-gray);
display: flex;
justify-content: center;
align-items: center;
}
#collapseBtn {
cursor: pointer;
border: none;
background: transparent;
font-size: 1.5rem;
color: var(--color-primary);
user-select:none;
transition: transform 0.3s ease;
}
#sidebar.collapsed #collapseBtn {
transform: rotate(180deg);
}
/* 主内容区 */
#mainContent {
flex: 1;
position: relative;
display: flex;
flex-direction: column;
background: var(--color-bg-main);
overflow: hidden;
}
/* 背景图片和canvas */
#backgroundLayer {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
overflow: hidden;
z-index: 0;
}
#backgroundLayer img#backgroundImage {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
filter: brightness(0.8);
user-select:none;
}
#backgroundLayer canvas#netCanvas {
position: absolute;
top: 0; left: 0;
width: 100%;
height: 100%;
pointer-events:none;
user-select:none;
}
#backgroundControl {
position: absolute;
right: 12px; bottom: 12px;
background: rgba(255 255 255 / 0.85);
border-radius: 12px;
padding: 6px 12px;
display: flex;
gap: 8px;
font-size: 0.85rem;
z-index: 15;
user-select:none;
}
#backgroundControl button {
border: none;
background: var(--color-primary);
color: white;
padding: 4px 10px;
border-radius: 8px;
cursor: pointer;
transition: background 0.2s;
}
#backgroundControl button:hover {
background: #7aa7f9;
}
#backgroundInput {
display: none;
}
/* 顶部工具栏 */
#toolbar {
height: 54px;
background: rgba(255 255 255 / 0.85);
border-bottom: 1px solid var(--color-silver-gray);
display: flex;
align-items: center;
padding: 0 12px;
z-index: 10;
user-select:none;
}
#searchInput {
flex-grow: 1;
height: 32px;
font-size: 1rem;
padding: 4px 8px;
border-radius: 6px;
border: 1px solid var(--color-silver-gray);
}
#toolbar button {
margin-left: 8px;
height: 32px;
border: none;
border-radius: 6px;
background: var(--color-primary);
color: white;
font-weight: 600;
padding: 0 12px;
cursor: pointer;
user-select:none;
transition: background 0.2s;
}
#toolbar button:disabled {
background: #9ec3ff88;
cursor: not-allowed;
}
#toolbar button:hover:not(:disabled) {
background: #7aa7f9;
}
#importFileInput {
display: none;
}
/* 货物列表表格 */
#cargoSection {
flex-grow: 1;
overflow-y: auto;
background: white;
margin: 12px;
border-radius: 12px;
box-shadow: 0 3px 8px rgba(0,0,0,0.1);
user-select:none;
position: relative;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
table-layout: fixed;
}
th,td {
border-bottom: 1px solid #ddd;
padding: 10px 8px;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
th {
background: var(--color-primary);
color: white;
user-select:none;
}
td .thumb {
width: 48px;
height: 48px;
object-fit: contain;
border-radius: 6px;
background: #f5f5f5;
cursor: pointer;
}
td .thumb.placeholder {
font-size: 1.5rem;
color: #ccc;
text-align: center;
line-height: 48px;
}
td input[type=checkbox] {
cursor: pointer;
transform: scale(1.2);
}
/* 操作按钮区 */
#actionBar {
position: absolute;
bottom: 14px;
right: 20px;
display: flex;
gap: 12px;
z-index: 10;
}
#actionBar button {
background: var(--color-primary);
border: none;
color: white;
cursor: pointer;
font-weight: 600;
font-size: 1rem;
padding: 10px 18px;
border-radius: 16px;
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
transition: background 0.25s, box-shadow 0.25s;
user-select:none;
position: relative;
overflow: hidden;
}
#actionBar button:hover {
background: #7aa7f9;
box-shadow: 0 4px 12px rgba(0,0,0,0.25);
}
/* 简单波纹动画 */
#actionBar button.ripple:after {
content: "";
position: absolute;
border-radius: 50%;
width: 100px;
height: 100px;
background: rgba(255 255 255 / 0.6);
animation: rippleEffect 0.6s ease-out;
pointer-events: none;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
}
@keyframes rippleEffect {
100% {
transform: translate(-50%, -50%) scale(2.5);
opacity: 0;
}
}
/* 模态弹窗背景 */
#modalOverlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
display: none;
justify-content: center;
align-items: center;
z-index: 30;
}
#modalOverlay.active {
display: flex;
}
/* 弹窗面板 */
#modalContent {
background: rgba(25,25,25,0.9);
border-radius: 16px;
width: 420px;
padding: 24px 30px;
color: white;
display: flex;
flex-direction: column;
user-select:text;
box-shadow: 0 0 24px #2e8cffcc;
}
#modalContent h2 {
margin:0 0 20px 0;
text-align:center;
font-weight: 600;
}
#modalContent label {
margin-top: 12px;
font-weight: 500;
font-size: 0.95rem;
}
#modalContent input[type="text"],
#modalContent input[type="number"],
#modalContent select {
margin-top: 6px;
padding: 8px 10px;
font-size: 1rem;
border-radius: 8px;
border:none;
}
#modalContent input[type="file"] {
margin-top: 6px;
}
#modalContent img.preview {
margin-top: 12px;
max-width: 160px;
border-radius: 12px;
object-fit: contain;
background: #fafafa;
}
#modalContent .buttons {
margin-top: 24px;
display: flex;
justify-content: center;
gap: 18px;
}
#modalContent button {
border:none;
padding: 10px 22px;
border-radius: 12px;
cursor: pointer;
font-weight: 600;
}
#modalContent button.saveBtn {
background: var(--color-primary);
color: white;
}
#modalContent button.cancelBtn {
background: #444;
color: #eee;
}
/* 搜索结果弹窗 */
#searchResultModal {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
display: none;
justify-content: center;
align-items: center;
z-index: 35;
user-select:none;
}
#searchResultModal.active {
display: flex;
}
#searchResultPanel {
background: white;
border-radius: 16px;
width: 360px;
max-height: 60vh;
overflow-y: auto;
box-shadow: 0 0 14px rgba(0,0,0,0.3);
padding: 20px;
animation: fadein 0.3s ease forwards;
}
@keyframes fadein {
from {opacity: 0; transform: translateY(20px);}
to {opacity: 1; transform: translateY(0);}
}
#searchResultPanel header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 14px;
}
#searchResultPanel header h3 {
margin: 0;
font-weight: 600;
font-size: 1.2rem;
}
#searchResultPanel header button.closeBtn {
background: transparent;
border:none;
font-size: 1.4rem;
cursor: pointer;
user-select:none;
}
#searchResultPanel ul {
list-style: none;
padding: 0; margin:0;
}
#searchResultPanel ul li {
padding: 8px 6px;
border-bottom: 1px solid #ddd;
cursor: pointer;
}
#searchResultPanel ul li:hover {
background: #f0f8ff;
}
</style>
</head>
<body>
<div id="container" tabindex="0" aria-label="货架货物管理系统">
<aside id="sidebar" aria-label="货架侧边栏" class="">
<header>
<img class="logo" id="logoImage" src="" alt="系统Logo" title="点击上传自定义Logo" tabindex="0" />
<label for="uploadLogoBtn" id="uploadLogoLabel" title="上传Logo">上传Logo</label>
<input type="file" accept="image/*" id="uploadLogoBtn" aria-label="上传Logo" />
<div class="title">货架管理</div>
</header>
<section id="shelfList" aria-label="货架列表">
<ul id="shelvesUl">
<!-- 货架列表项 -->
</ul>
<button id="addShelfBtn" aria-label="添加货架">+ 添加货架</button>
</section>
<footer id="sidebarFooter">
<button id="collapseBtn" aria-label="切换侧边栏折叠状态">⯈</button>
</footer>
</aside>
<section id="mainContent" aria-label="主内容区">
<div id="backgroundLayer" aria-hidden="true">
<img id="backgroundImage" alt="背景图片" />
<canvas id="netCanvas" width="0" height="0"></canvas>
</div>
<div id="backgroundControl" aria-label="背景图片控制">
<label for="backgroundInput" style="cursor:pointer; user-select:none;" tabindex="0">更换背景</label>
<input type="file" id="backgroundInput" accept="image/*" aria-label="上传背景图片" />
<button id="clearBackgroundBtn" aria-label="清除背景图片">清除背景</button>
</div>
<nav id="toolbar" aria-label="工具栏">
<input type="search" id="searchInput" placeholder="搜索货物..." aria-label="货物搜索" />
<label for="importFileInput" style="background: var(--color-primary); color: white; border-radius:6px; cursor:pointer; padding:6px 12px;" tabindex="0">导入Excel</label>
<input type="file" id="importFileInput" accept=".xlsx,.xls" aria-label="导入Excel文件" />
<button id="exportBtn" aria-label="导出Excel">导出Excel</button>
<button id="saveBtn" aria-label="保存数据" disabled>保存</button>
</nav>
<section id="cargoSection" aria-label="货物列表展示">
<table aria-describedby="货架货物列表">
<thead>
<tr>
<th><input type="checkbox" id="selectAllCheckbox" aria-label="全选货物" /></th>
<th>图片</th>
<th>品名</th>
<th>种类</th>
<th>数量</th>
<th>金额</th>
</tr>
</thead>
<tbody id="cargoTbody">
<!-- 货物列表 -->
</tbody>
</table>
</section>
<div id="actionBar" aria-label="货物操作按钮区">
<button id="addCargoBtn" aria-label="添加货物">添加</button>
<button id="editCargoBtn" aria-label="编辑货物" disabled>编辑</button>
<button id="deleteCargoBtn" aria-label="删除货物" disabled>删除</button>
<button id="moveCargoBtn" aria-label="移动货物" disabled>移动</button>
</div>
</section>
</div>
<!-- 添加/编辑货物弹窗 -->
<div id="modalOverlay" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
<div id="modalContent">
<h2 id="modalTitle">添加货物</h2>
<form id="cargoForm" autocomplete="off">
<label for="cargoName">品名</label>
<input type="text" id="cargoName" name="cargoName" required aria-required="true" autocomplete="off" />
<label for="cargoType">种类</label>
<input type="text" id="cargoType" name="cargoType" required aria-required="true" autocomplete="off" />
<label for="cargoQuantity">数量</label>
<input type="number" id="cargoQuantity" name="cargoQuantity" min="0" required aria-required="true" autocomplete="off" />
<label for="cargoAmount">金额</label>
<input type="number" id="cargoAmount" name="cargoAmount" min="0" step="0.01" required aria-required="true" autocomplete="off" />
<label for="cargoImage">图片(可选)</label>
<input type="file" id="cargoImage" name="cargoImage" accept="image/*" aria-label="上传货物图片" />
<img src="" alt="图片预览" id="cargoImagePreview" class="preview" aria-hidden="true" style="display:none" />
<div class="buttons">
<button type="submit" class="saveBtn" aria-label="保存货物">保存</button>
<button type="button" class="cancelBtn" aria-label="取消添加编辑">取消</button>
</div>
</form>
</div>
</div>
<!-- 搜索结果弹窗 -->
<div id="searchResultModal" role="dialog" aria-modal="true" aria-labelledby="searchResultTitle">
<div id="searchResultPanel">
<header>
<h3 id="searchResultTitle">搜索结果</h3>
<button class="closeBtn" aria-label="关闭搜索结果">×</button>
</header>
<ul id="searchResultList" tabindex="0" aria-live="polite"></ul>
</div>
</div>
<!-- 引入SheetJS -->
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.19.1/dist/xlsx.full.min.js"></script>
<script>
(() => {
// ------------------------------------
// 1. 数据结构
// 货架列表,每个货架有id, name, items数组
// 货物items: id, 品名, 种类, 数量, 金额, 图片Base64
const STORAGE_KEY = 'lightShelfDataV1';
let state = {
shelves: [],
selectedShelfId: null,
selectedCargoIds: new Set(),
unsavedChanges: false,
logoBase64: '',
backgroundBase64: '',
};
// ------------------------------------
// 2. DOM元素
const sidebar = document.getElementById('sidebar');
const collapseBtn = document.getElementById('collapseBtn');
const shelvesUl = document.getElementById('shelvesUl');
const addShelfBtn = document.getElementById('addShelfBtn');
const logoImage = document.getElementById('logoImage');
const uploadLogoBtn = document.getElementById('uploadLogoBtn');
const backgroundInput = document.getElementById('backgroundInput');
const backgroundImage = document.getElementById('backgroundImage');
const clearBackgroundBtn = document.getElementById('clearBackgroundBtn');
const netCanvas = document.getElementById('netCanvas');
const ctx = netCanvas.getContext('2d');
const searchInput = document.getElementById('searchInput');
const importFileInput = document.getElementById('importFileInput');
const exportBtn = document.getElementById('exportBtn');
const saveBtn = document.getElementById('saveBtn');
const cargoTbody = document.getElementById('cargoTbody');
const selectAllCheckbox = document.getElementById('selectAllCheckbox');
const addCargoBtn = document.getElementById('addCargoBtn');
const editCargoBtn = document.getElementById('editCargoBtn');
const deleteCargoBtn = document.getElementById('deleteCargoBtn');
const moveCargoBtn = document.getElementById('moveCargoBtn');
// 弹窗
const modalOverlay = document.getElementById('modalOverlay');
const cargoForm = document.getElementById('cargoForm');
const modalTitle = document.getElementById('modalTitle');
const cargoName = document.getElementById('cargoName');
const cargoType = document.getElementById('cargoType');
const cargoQuantity = document.getElementById('cargoQuantity');
const cargoAmount = document.getElementById('cargoAmount');
const cargoImageInput = document.getElementById('cargoImage');
const cargoImagePreview = document.getElementById('cargoImagePreview');
const cancelBtn = modalOverlay.querySelector('.cancelBtn');
// 搜索结果弹窗
const searchResultModal = document.getElementById('searchResultModal');
const searchResultList = document.getElementById('searchResultList');
const searchResultCloseBtn = searchResultModal.querySelector('.closeBtn');
// ------------------------------------
// 3. 工具函数
// 生成唯一id(简单版)
function uuid() {
return 'id-' + Math.random().toString(36).substr(2, 9);
}
function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
state.unsavedChanges = false;
saveBtn.disabled = true;
}
function loadState() {
const d = localStorage.getItem(STORAGE_KEY);
if(d) {
try {
const parsed = JSON.parse(d);
if(parsed.shelves && Array.isArray(parsed.shelves)) {
state = {...state, ...parsed};
}
} catch(e) {
console.warn('读取本地存储数据失败', e);
}
}
}
// 标记有未保存
function markUnsaved() {
if(!state.unsavedChanges) {
state.unsavedChanges = true;
saveBtn.disabled = false;
}
}
// 载入logo
function renderLogo() {
if(state.logoBase64) {
logoImage.src = state.logoBase64;
} else {
// 预设svg替代简单logo
logoImage.src = 'data:image/svg+xml;utf8,' + encodeURIComponent(`
<svg width="40" height="40" xmlns="http://www.w3.org/2000/svg">
<rect width="40" height="40" rx="6" ry="6" fill="#a1c4fd"/>
<text x="50%" y="55%" dominant-baseline="middle" text-anchor="middle" fill="white" font-weight="bold" font-size="20">货</text>
</svg>
`);
}
}
// 载入背景
function renderBackground() {
if(state.backgroundBase64) {
backgroundImage.src = state.backgroundBase64;
backgroundImage.style.display = 'block';
} else {
backgroundImage.src = '';
backgroundImage.style.display = 'none';
}
}
// 重新渲染货架列表
function renderShelves() {
shelvesUl.innerHTML = '';
for(const shelf of state.shelves) {
const li = document.createElement('li');
li.dataset.id = shelf.id;
li.classList.add('shelf-item');
li.setAttribute('tabindex', '0');
li.setAttribute('role', 'button');
li.setAttribute('aria-pressed', (shelf.id === state.selectedShelfId) ? 'true' : 'false');
// 折叠时tooltip显示名称
if(sidebar.classList.contains('collapsed')) {
li.classList.add('collapsed-tooltip');
li.setAttribute('data-name', shelf.name);
li.textContent = shelf.name[0];
} else {
// 展开时显示完整
li.textContent = shelf.name;
// 添加重命名逻辑(双击进入编辑)
li.ondblclick = (e) => {
e.stopPropagation();
enterShelfRename(li, shelf);
};
// 添加删除按钮
const delBtn = document.createElement('button');
delBtn.className = 'deleteShelf';
delBtn.textContent = '删';
delBtn.title = '删除货架';
delBtn.disabled = shelf.items && shelf.items.length > 0; // 仅空货架可删
delBtn.onclick = (ev) => {
ev.stopPropagation();
if(confirm(`确定删除货架【${shelf.name}】?`)) {
state.shelves = state.shelves.filter(s => s.id !== shelf.id);
if(state.selectedShelfId === shelf.id) {
state.selectedShelfId = state.shelves.length ? state.shelves[0].id : null;
state.selectedCargoIds.clear();
}
markUnsaved();
renderShelves();
renderCargoTable();
}
};
li.appendChild(delBtn);
}
// 点击切换选中货架
li.onclick = () => {
if(state.selectedShelfId !== shelf.id) {
state.selectedShelfId = shelf.id;
state.selectedCargoIds.clear();
renderShelves();
renderCargoTable();
markUnsaved();
}
};
li.onkeypress = (e) => {
if(e.key === 'Enter' || e.key===' ') {
li.click();
e.preventDefault();
}
};
shelvesUl.appendChild(li);
}
}
// 进入货架重命名输入框
function enterShelfRename(liElem, shelfObj) {
liElem.innerHTML = '';
const input = document.createElement('input');
input.type = 'text';
input.value = shelfObj.name;
input.className = 'rename';
input.setAttribute('aria-label', '重命名货架');
liElem.appendChild(input);
input.focus();
input.select();
// 失去焦点或回车确认
function commitRename() {
const newName = input.value.trim() || shelfObj.name;
shelfObj.name = newName;
markUnsaved();
renderShelves();
}
input.onblur = commitRename;
input.onkeydown = (e) => {
if(e.key === 'Enter') {
commitRename();
} else if(e.key === 'Escape') {
renderShelves();
}
}
}
// 渲染货物列表
function renderCargoTable() {
cargoTbody.innerHTML = '';
if(!state.selectedShelfId) return;
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) return;
for(const cargo of shelf.items) {
const tr = document.createElement('tr');
// 复选框
const tdCheck = document.createElement('td');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = state.selectedCargoIds.has(cargo.id);
checkbox.setAttribute('aria-label', `选择货物 ${cargo["品名"]}`);
checkbox.onchange = (e) => {
if(e.target.checked) {
state.selectedCargoIds.add(cargo.id);
} else {
state.selectedCargoIds.delete(cargo.id);
}
updateCargoActionButtons();
};
tdCheck.appendChild(checkbox);
tr.appendChild(tdCheck);
// 图片
const tdImg = document.createElement('td');
if(cargo['图片']) {
const img = document.createElement('img');
img.src = cargo['图片'];
img.alt = cargo['品名'] + ' 图片';
img.className = 'thumb';
img.tabIndex = 0;
// 点击查看大图(简单alert示意)
img.onclick = () => {
openImagePreview(cargo['图片'], cargo['品名']);
};
img.onkeypress = (e) => { if(e.key==='Enter' || e.key===' ') img.click(); };
tdImg.appendChild(img);
} else {
const ph = document.createElement('div');
ph.className = 'thumb placeholder';
ph.textContent = '/';
tdImg.appendChild(ph);
}
tr.appendChild(tdImg);
// 品名
const tdName = document.createElement('td');
tdName.textContent = cargo['品名'];
tr.appendChild(tdName);
// 种类
const tdType = document.createElement('td');
tdType.textContent = cargo['种类'];
tr.appendChild(tdType);
// 数量
const tdQty = document.createElement('td');
tdQty.textContent = cargo['数量'];
tr.appendChild(tdQty);
// 金额
const tdAmt = document.createElement('td');
tdAmt.textContent = cargo['金额'];
tr.appendChild(tdAmt);
cargoTbody.appendChild(tr);
}
// 重置复选框
selectAllCheckbox.checked = false;
updateCargoActionButtons();
}
// 更新按钮状态
function updateCargoActionButtons() {
const selectedCount = state.selectedCargoIds.size;
editCargoBtn.disabled = selectedCount !== 1;
deleteCargoBtn.disabled = selectedCount === 0;
moveCargoBtn.disabled = selectedCount === 0;
}
// 选择全选/取消全选
selectAllCheckbox.onchange = (e) => {
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) return;
if(e.target.checked) {
shelf.items.forEach(i => state.selectedCargoIds.add(i.id));
} else {
state.selectedCargoIds.clear();
}
renderCargoTable();
};
// 弹窗打开关闭
function openModal(isEdit=false, cargoData=null) {
modalOverlay.classList.add('active');
modalOverlay.setAttribute('aria-hidden', 'false');
cargoForm.reset();
cargoImagePreview.style.display = 'none';
if(isEdit && cargoData) {
modalTitle.textContent = '编辑货物';
cargoName.value = cargoData['品名'];
cargoType.value = cargoData['种类'];
cargoQuantity.value = cargoData['数量'];
cargoAmount.value = cargoData['金额'];
if(cargoData['图片']) {
cargoImagePreview.src = cargoData['图片'];
cargoImagePreview.style.display = 'block';
}
} else {
modalTitle.textContent = '添加货物';
}
}
function closeModal() {
modalOverlay.classList.remove('active');
modalOverlay.setAttribute('aria-hidden', 'true');
}
cancelBtn.onclick = closeModal;
modalOverlay.onclick = e => {
if(e.target === modalOverlay) closeModal();
};
// 货物图片预览点击
function openImagePreview(src, name) {
// 简单实现用alert替代,可以替换成更复杂的弹窗大图
const imgWin = window.open('');
imgWin.document.write(`<title>${name} 图片预览</title><img src="${src}" style="max-width:100vw; max-height:100vh;" alt="${name}大图" />`);
}
// 处理新增货架
addShelfBtn.onclick = () => {
let newName = `新货架${state.shelves.length + 1}`;
let newId = uuid();
state.shelves.push({id:newId, name:newName, items:[]});
if(!state.selectedShelfId) {
state.selectedShelfId = newId;
}
markUnsaved();
renderShelves();
renderCargoTable();
};
// 处理Logo上传
logoImage.onclick = () => uploadLogoBtn.click();
uploadLogoBtn.onchange = e => {
const file = e.target.files[0];
if(file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = () => {
state.logoBase64 = reader.result;
renderLogo();
markUnsaved();
};
reader.readAsDataURL(file);
}
uploadLogoBtn.value = '';
};
// 背景上传与清理
backgroundInput.onchange = e => {
const file = e.target.files[0];
if(file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = () => {
state.backgroundBase64 = reader.result;
renderBackground();
markUnsaved();
};
reader.readAsDataURL(file);
}
backgroundInput.value = '';
};
clearBackgroundBtn.onclick = () => {
state.backgroundBase64 = '';
renderBackground();
markUnsaved();
};
// 侧栏折叠切换
collapseBtn.onclick = () => {
sidebar.classList.toggle('collapsed');
renderShelves();
};
// 保存按钮点击
saveBtn.onclick = () => saveState();
// 导入Excel
importFileInput.onchange = e => {
const file = e.target.files[0];
if(!file) return;
const reader = new FileReader();
reader.onload = (evt) => {
try {
const data = new Uint8Array(evt.target.result);
const workbook = XLSX.read(data, {type: 'array'});
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, {defval:''});
if(!Array.isArray(jsonData)) throw new Error('导入数据格式错误');
// 校验必要字段
const requiredFields = ["品名","种类","数量","金额","图片Base64"];
for(const row of jsonData) {
for(const f of requiredFields) {
if(!(f in row)) {
alert(`导入错误: 缺少字段【${f}】,请使用正确模板。`);
importFileInput.value = "";
return;
}
}
}
// 导入简单合并到当前选中货架 items
if(!state.selectedShelfId) {
alert('请先选择一个货架导入货物');
importFileInput.value = "";
return;
}
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) {
alert('选中货架无效');
importFileInput.value = "";
return;
}
// 转换字段(确保图片字段为正确base64,如果无则空字符串)
for(const item of jsonData) {
item['数量'] = Number(item['数量']) || 0;
item['金额'] = Number(item['金额']) || 0;
item['图片'] = item['图片Base64'] || '';
delete item['图片Base64'];
item.id = uuid();
}
shelf.items.push(...jsonData);
markUnsaved();
renderCargoTable();
alert('导入成功!');
} catch(err) {
alert('导入失败,文件格式异常');
console.error(err);
}
importFileInput.value = "";
};
reader.readAsArrayBuffer(file);
};
// 导出Excel
exportBtn.onclick = () => {
if(!state.selectedShelfId) {
alert('请选择一个货架导出');
return;
}
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) return;
const exportData = shelf.items.map(i=>({
"品名": i['品名'],
"种类": i['种类'],
"数量": i['数量'],
"金额": i['金额'],
"图片Base64": i['图片'] || ''
}));
const ws = XLSX.utils.json_to_sheet(exportData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, shelf.name || '货物');
const timecode = new Date().toISOString().replace(/[:\-T]/g,'').slice(0,14);
const fileName = `货架_${shelf.name || '导出'}_${timecode}.xlsx`;
XLSX.writeFile(wb, fileName);
};
// 添加货物 (弹窗)
addCargoBtn.onclick = () => {
if(!state.selectedShelfId) {
alert('请选择一个货架先');
return;
}
openModal(false);
};
// 编辑货物
editCargoBtn.onclick = () => {
if(state.selectedCargoIds.size !== 1) return;
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) return;
const id = [...state.selectedCargoIds][0];
const cargo = shelf.items.find(i => i.id === id);
if(!cargo) return;
openModal(true, cargo);
};
// 删除货物
deleteCargoBtn.onclick = () => {
if(state.selectedCargoIds.size === 0) return;
if(!confirm(`确定删除选中的${state.selectedCargoIds.size}个货物?`)) return;
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) return;
shelf.items = shelf.items.filter(i => !state.selectedCargoIds.has(i.id));
state.selectedCargoIds.clear();
markUnsaved();
renderCargoTable();
};
// 移动货物(简化实现弹prompt选择目标货架名称)
moveCargoBtn.onclick = () => {
if(state.selectedCargoIds.size === 0) return;
const targetShelfName = prompt('请输入目标货架名称:');
if(!targetShelfName) return;
const targetShelf = state.shelves.find(s => s.name === targetShelfName.trim());
if(!targetShelf) {
alert('无此货架,请先创建对应货架');
return;
}
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) return;
const movingItems = shelf.items.filter(i => state.selectedCargoIds.has(i.id));
// 移除当前货架对应货物
shelf.items = shelf.items.filter(i => !state.selectedCargoIds.has(i.id));
// 添加到目标货架
targetShelf.items.push(...movingItems);
state.selectedCargoIds.clear();
markUnsaved();
renderCargoTable();
};
// 弹窗提交
cargoForm.onsubmit = e => {
e.preventDefault();
if(!state.selectedShelfId) {
alert('请选择一个货架');
return;
}
const shelf = state.shelves.find(s => s.id === state.selectedShelfId);
if(!shelf) return;
// 验证数量金额
if(cargoQuantity.value < 0 || cargoAmount.value < 0) {
alert('数量和金额不能为负数');
return;
}
// 是否编辑
let editingId = null;
if(state.selectedCargoIds.size === 1) {
editingId = [...state.selectedCargoIds][0];
}
// 读取图片Base64(异步)
const file = cargoImageInput.files[0];
if(file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = () => {
const imgBase64 = reader.result;
saveCargo(editingId, imgBase64);
};
reader.readAsDataURL(file);
} else {
saveCargo(editingId, null);
}
function saveCargo(editId, imgBase64) {
if(editId) {
// 编辑
const cargo = shelf.items.find(i => i.id === editId);
if(!cargo) return;
cargo['品名'] = cargoName.value.trim();
cargo['种类'] = cargoType.value.trim();
cargo['数量'] = Number(cargoQuantity.value);
cargo['金额'] = Number(cargoAmount.value);
if(imgBase64 !== null) cargo['图片'] = imgBase64;
} else {
// 新增
shelf.items.push({
id: uuid(),
"品名": cargoName.value.trim(),
"种类": cargoType.value.trim(),
"数量": Number(cargoQuantity.value),
"金额": Number(cargoAmount.value),
"图片": imgBase64 || ''
});
}
markUnsaved();
renderCargoTable();
closeModal();
state.selectedCargoIds.clear();
updateCargoActionButtons();
}
};
cargoImageInput.onchange = e => {
const file = e.target.files[0];
if(file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = () => {
cargoImagePreview.src = reader.result;
cargoImagePreview.style.display = 'block';
};
reader.readAsDataURL(file);
}
};
// 搜索处理
searchInput.oninput = () => {
const kw = searchInput.value.trim().toLowerCase();
if(!kw) {
searchResultModal.classList.remove('active');
return;
}
// 全仓库所有货物搜索
let results = [];
for(const shelf of state.shelves) {
for(const item of shelf.items) {
if(item['品名'].toLowerCase().includes(kw) || item['种类'].toLowerCase().includes(kw)) {
results.push({...item, shelfName:shelf.name});
}
}
}
renderSearchResults(results);
};
searchResultCloseBtn.onclick = () => {
searchResultModal.classList.remove('active');
};
searchResultModal.onclick = e => {
if(e.target === searchResultModal) searchResultModal.classList.remove('active');
};
function renderSearchResults(arr) {
searchResultList.innerHTML = '';
if(arr.length === 0) {
const li = document.createElement('li');
li.textContent = '无匹配结果';
searchResultList.appendChild(li);
} else {
for(const r of arr) {
const li = document.createElement('li');
li.tabIndex = 0;
li.textContent = `[${r.shelfName}] ${r['品名']} (${r['种类']}) 数量:${r['数量']} 金额:${r['金额']}`;
li.onclick = () => {
searchResultModal.classList.remove('active');
const shelf = state.shelves.find(s => s.name === r.shelfName);
if(!shelf) return;
state.selectedShelfId = shelf.id;
state.selectedCargoIds.clear();
state.selectedCargoIds.add(r.id);
renderShelves();
renderCargoTable();
updateCargoActionButtons();
};
li.onkeypress = e => {
if(e.key === 'Enter' || e.key === ' ') li.click();
};
searchResultList.appendChild(li);
}
}
searchResultModal.classList.add('active');
}
// 网状粒子线条动画:简单版
let points = [];
const maxDist = 150;
function resizeCanvas() {
netCanvas.width = netCanvas.clientWidth;
netCanvas.height = netCanvas.clientHeight;
}
function generatePoints() {
points = [];
for(let i=0; i < 50; i++) {
points.push({
x: Math.random()*netCanvas.width,
y: Math.random()*netCanvas.height,
vx: (Math.random()-0.5)*0.3,
vy: (Math.random()-0.5)*0.3,
});
}
}
function draw() {
ctx.clearRect(0,0,netCanvas.width, netCanvas.height);
// 移动点
points.forEach(p=>{
p.x+=p.vx;
p.y+=p.vy;
if(p.x<0 || p.x>netCanvas.width) p.vx*=-1;
if(p.y<0 || p.y>netCanvas.height) p.vy*=-1;
// 画点
ctx.beginPath();
ctx.arc(p.x, p.y, 2, 0, Math.PI*2);
ctx.fillStyle = 'rgba(161,196,253,0.7)';
ctx.fill();
});
// 连线
for(let i=0; i < points.length; i++) {
for(let j=i+1; j < points.length; j++) {
const dist = Math.hypot(points[i].x - points[j].x, points[i].y - points[j].y);
if(dist < maxDist) {
ctx.beginPath();
ctx.strokeStyle = `rgba(161,196,253,${1-dist/maxDist})`;
ctx.lineWidth=1;
ctx.moveTo(points[i].x, points[i].y);
ctx.lineTo(points[j].x, points[j].y);
ctx.stroke();
}
}
}
requestAnimationFrame(draw);
}
function onResize() {
resizeCanvas();
generatePoints();
}
window.addEventListener('resize', onResize);
// 安全关闭提醒
window.addEventListener('beforeunload', e => {
if(state.unsavedChanges) {
e.preventDefault();
e.returnValue = '';
return '';
}
});
// 页面初始化
function init() {
loadState();
renderLogo();
renderBackground();
renderShelves();
renderCargoTable();
updateCargoActionButtons();
onResize();
}
init();
// 点击波纹音效简单示范
// 全局委托为方便
document.body.addEventListener('click', e => {
// 波纹
if(e.target.tagName === 'BUTTON' || e.target.tagName==='INPUT' || e.target.tagName==='LABEL') {
const btn = e.target.closest('button');
if(btn) {
btn.classList.remove('ripple');
void btn.offsetWidth; // 重触发动画
btn.classList.add('ripple');
// 轻柔音效 - 用简单的 Web Audio API 呈现短音
playClickSound();
}
}
});
function playClickSound() {
const ctxAudio = new AudioContext();
const o = ctxAudio.createOscillator();
const g = ctxAudio.createGain();
o.frequency.value = 600;
o.type = 'sine';
g.gain.setValueAtTime(0.1, ctxAudio.currentTime);
g.gain.exponentialRampToValueAtTime(0.0001, ctxAudio.currentTime + 0.1);
o.connect(g);
g.connect(ctxAudio.destination);
o.start();
o.stop(ctxAudio.currentTime + 0.1);
}
})();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>增删改查 + Excel导入导出示例</title>
<style>
body { font-family: sans-serif; margin: 20px; background:#f5f7fa;}
table { border-collapse: collapse; width: 100%; background: white; }
th, td { border: 1px solid #ccc; padding: 8px; text-align:center; }
th { background: #4caf50; color: white; }
button { padding: 6px 12px; margin: 5px; cursor: pointer; }
#modalOverlay {
position: fixed; inset: 0;
background: rgba(0,0,0,0.4);
display: none;
justify-content: center;
align-items: center;
z-index: 9999;
}
#modalOverlay.active { display: flex; }
#modalContent {
background: white;
padding: 20px 25px;
border-radius: 8px;
width: 320px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
#modalContent label { display: block; margin: 10px 0 4px; }
#modalContent input[type="text"], #modalContent input[type="number"] {
width: 100%;
padding: 6px 8px;
box-sizing: border-box;
}
</style>
</head>
<body>
<h2>货物管理系统示例(增删改查 + Excel导入导出)</h2>
<div>
<button id="btnAdd">添加货物</button>
<button id="btnDelete" disabled>删除选中</button>
<button id="btnSave" disabled>保存到本地</button>
<label style="cursor:pointer; background:#2196f3; color:#fff; padding:6px 12px; border-radius:4px;">
导入Excel<input type="file" id="fileImport" accept=".xlsx,.xls" style="display:none" />
</label>
<button id="btnExport">导出Excel</button>
</div>
<table aria-label="货物列表" style="margin-top:10px;">
<thead>
<tr>
<th><input type="checkbox" id="checkAll" aria-label="全选"/></th>
<th>品名</th>
<th>种类</th>
<th>数量</th>
<th>金额</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tbodyData">
<!-- 动态数据行 -->
</tbody>
</table>
<!-- 弹窗模态 -->
<div id="modalOverlay" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
<div id="modalContent">
<h3 id="modalTitle">添加货物</h3>
<form id="formData">
<label for="inputName">品名</label>
<input type="text" id="inputName" name="品名" required />
<label for="inputType">种类</label>
<input type="text" id="inputType" name="种类" required />
<label for="inputQty">数量</label>
<input type="number" id="inputQty" name="数量" min="0" required />
<label for="inputAmt">金额</label>
<input type="number" id="inputAmt" name="金额" min="0" step="0.01" required />
<div style="margin-top:15px; text-align:right;">
<button type="button" id="btnCancel">取消</button>
<button type="submit" id="btnSubmit">保存</button>
</div>
</form>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>
<script>
// 数据存储Key
const STORAGE_KEY = 'myGoodsDataV1';
// 当前全部数据
let dataList = [];
// 编辑模式id,null表示新增
let editIndex = null;
const tbodyData = document.getElementById('tbodyData');
const btnAdd = document.getElementById('btnAdd');
const btnDelete = document.getElementById('btnDelete');
const btnSave = document.getElementById('btnSave');
const fileImport = document.getElementById('fileImport');
const btnExport = document.getElementById('btnExport');
const checkAll = document.getElementById('checkAll');
const modalOverlay = document.getElementById('modalOverlay');
const modalTitle = document.getElementById('modalTitle');
const formData = document.getElementById('formData');
const inputName = document.getElementById('inputName');
const inputType = document.getElementById('inputType');
const inputQty = document.getElementById('inputQty');
const inputAmt = document.getElementById('inputAmt');
const btnCancel = document.getElementById('btnCancel');
function saveLocal(){
localStorage.setItem(STORAGE_KEY, JSON.stringify(dataList));
btnSave.disabled = true;
alert('数据已保存到本地浏览器');
}
function loadLocal(){
const d = localStorage.getItem(STORAGE_KEY);
if(d){
try {
dataList = JSON.parse(d);
} catch(e){
dataList = [];
}
}
}
// 渲染数据表格
function renderTable(){
tbodyData.innerHTML = '';
dataList.forEach((item,i)=>{
const tr = document.createElement('tr');
tr.dataset.index = i;
// 复选框
const td_check = document.createElement('td');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'rowCheckbox';
cb.addEventListener('change', updateDeleteBtn);
td_check.appendChild(cb);
tr.appendChild(td_check);
// 品名
const td_name = document.createElement('td');
td_name.textContent = item['品名'];
tr.appendChild(td_name);
// 种类
const td_type = document.createElement('td');
td_type.textContent = item['种类'];
tr.appendChild(td_type);
// 数量
const td_qty = document.createElement('td');
td_qty.textContent = item['数量'];
tr.appendChild(td_qty);
// 金额
const td_amt = document.createElement('td');
td_amt.textContent = item['金额'];
tr.appendChild(td_amt);
// 操作编辑按钮
const td_op = document.createElement('td');
const btnEdit = document.createElement('button');
btnEdit.textContent = '编辑';
btnEdit.addEventListener('click', ()=>{
showEditModal(i);
});
td_op.appendChild(btnEdit);
tr.appendChild(td_op);
tbodyData.appendChild(tr);
});
updateDeleteBtn();
checkAll.checked = false;
}
// 更新删除按钮状态
function updateDeleteBtn(){
const cbs = document.querySelectorAll('.rowCheckbox');
const checkedCount = [...cbs].filter(cb=>cb.checked).length;
btnDelete.disabled = checkedCount === 0;
checkAll.checked = (checkedCount >0) && (checkedCount === cbs.length);
}
checkAll.addEventListener('change', () => {
const cbs = document.querySelectorAll('.rowCheckbox');
cbs.forEach(cb=>cb.checked = checkAll.checked);
updateDeleteBtn();
});
btnAdd.addEventListener('click', () => {
editIndex = null;
modalTitle.textContent = '添加货物';
formData.reset();
modalOverlay.classList.add('active');
inputName.focus();
});
btnCancel.addEventListener('click', () => {
modalOverlay.classList.remove('active');
});
formData.addEventListener('submit', (e)=>{
e.preventDefault();
const item = {
'品名': inputName.value.trim(),
'种类': inputType.value.trim(),
'数量': Number(inputQty.value),
'金额': Number(inputAmt.value)
};
if(editIndex === null){
dataList.push(item);
} else {
dataList[editIndex] = item;
}
btnSave.disabled = false;
renderTable();
modalOverlay.classList.remove('active');
});
function showEditModal(index){
editIndex = index;
modalTitle.textContent = '编辑货物';
const item = dataList[index];
inputName.value = item['品名'];
inputType.value = item['种类'];
inputQty.value = item['数量'];
inputAmt.value = item['金额'];
modalOverlay.classList.add('active');
inputName.focus();
}
btnDelete.addEventListener('click', () => {
if(!confirm('确定删除选中项吗?')) return;
const cbs = document.querySelectorAll('.rowCheckbox');
// 反向遍历避免下标错乱
for(let i=cbs.length-1; i>=0; i--){
if(cbs[i].checked){
dataList.splice(i,1);
}
}
btnSave.disabled = false;
renderTable();
});
// 导入Excel
fileImport.addEventListener('change', (e) => {
const f = e.target.files[0];
if(!f) return;
const reader = new FileReader();
reader.onload = (evt) => {
const wdata = new Uint8Array(evt.target.result);
const workbook = XLSX.read(wdata, {type:'array'});
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, {defval:""});
// 校验字段
const requiredFields = ['品名','种类','数量','金额'];
const invalid = jsonData.some(row => requiredFields.some(f=> !(f in row)));
if(invalid){
alert('导入失败:文件缺少必要字段,请使用正确模板');
return;
}
dataList = jsonData.map(r=>{
return {
'品名': r['品名'],
'种类': r['种类'],
'数量': Number(r['数量'])||0,
'金额': Number(r['金额'])||0,
};
});
btnSave.disabled = false;
renderTable();
alert('导入成功,共导入' + dataList.length + '条数据');
};
reader.readAsArrayBuffer(f);
// 清空选择,方便下次同文件导入
e.target.value = '';
});
// 导出Excel
btnExport.addEventListener('click', () => {
if(dataList.length === 0){
alert('当前无数据导出');
return;
}
const ws = XLSX.utils.json_to_sheet(dataList);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, '货物列表');
// 生成时间戳,格式YYYYMMDD_HHMMSS
const now = new Date();
const pad = n => n.toString().padStart(2,'0');
const fn = `货物导出_${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.xlsx`;
XLSX.writeFile(wb, fn);
});
// 保存按钮
btnSave.addEventListener('click', () => {
saveLocal();
});
// 初始化
function init(){
loadLocal();
renderTable();
btnSave.disabled = true;
}
window.addEventListener('beforeunload', e => {
if(!btnSave.disabled){
e.preventDefault();
e.returnValue = '';
}
});
init();
</script>
</body>
</html>