设置cell选中后一段时间颜色自动消失

本文介绍如何实现个性化点击效果并优化系统的样式,在TableView中通过特定代码实现在选择和取消选择时的不同表现,包括调整选择样式为无、蓝色、灰色或默认样式。
//个性化点击效果
-(
void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    [
self performSelector:@selector(deselect) withObject:nil afterDelay:0.2f];
   
}
-(
void)deselect{
    [
self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

//============系统样式===================
self.selectionStyle = UITableViewCellSelectionStyleDefault;
   
   
/**
     *  UITableViewCellSelectionStyleNone,//
没有现象
     UITableViewCellSelectionStyleBlue, 
灰色
     UITableViewCellSelectionStyleGray,
     UITableViewCellSelectionStyleDefault
     */
下面是一个**完整的、可直接运行的 HTML 文件**,它结合了你之前的需求: - ✅ 基于网页的数独游戏 - ✅ 支持用户输入、求解验证、显示答案、重置功能 - ✅ **新增:随机生成合法且唯一解的数独谜题** - ✅ 难度选择(简单 / 中等 / 困难) - ✅ 界面美观 + 交互反馈 --- ### 📄 完整代码(复制保存为 `sudoku.html` 即可运行) ```html <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>数独游戏</title> <style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; background-color: #f4f7fa; margin: 0; padding: 20px; } h1 { color: #333; margin-bottom: 10px; } .subtitle { color: #666; font-size: 16px; } .controls { margin: 20px 0; display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; } button { padding: 10px 18px; font-size: 16px; cursor: pointer; border: none; background-color: #4caf50; color: white; border-radius: 5px; transition: all 0.2s ease; } button:hover { background-color: #45a049; } button:active { transform: scale(0.98); } button#reset-btn { background-color: #ff9800; } button#reset-btn:hover { background-color: #e68a00; } button#solve-btn { background-color: #2196f3; } button#solve-btn:hover { background-color: #0b7dda; } button#answer-btn { background-color: #9c27b0; } button#answer-btn:hover { background-color: #7b1fa2; } .sudoku-board { display: grid; grid-template-columns: repeat(9, 50px); grid-template-rows: repeat(9, 50px); gap: 1px; border: 2px solid #333; box-shadow: 0 4px 15px rgba(0,0,0,0.1); } .cell { width: 50px; height: 50px; background-color: #fff; border: 1px solid #ccc; display: flex; justify-content: center; align-items: center; font-size: 20px; font-weight: bold; cursor: pointer; user-select: none; } /* 加粗边框分隔 3x3 宫格 */ .cell:nth-child(3n) { border-right-width: 2px !important; } .cell:nth-child(9n) { border-right-width: 1px !important; } .cell:nth-child(n+19):nth-child(-n+27), .cell:nth-child(n+46):nth-child(-n+54) { border-bottom: 2px solid #333; } .cell:nth-child(27n + 1), .cell:nth-child(27n + 4), .cell:nth-child(27n + 7) { border-left: 2px solid #333; } /* 初始数字样式 */ .fixed { background-color: #e0f7fa; color: #0277bd; } /* 用户输入的数字 */ .editable { color: #d32f2f; } /* 选中状态 */ .selected { background-color: #bbdefb !important; } /* 错误标记 */ .error { color: red !important; } /* 模态框 */ .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); justify-content: center; align-items: center; z-index: 1000; } .modal-content { background: white; padding: 20px; border-radius: 10px; text-align: center; width: 300px; box-shadow: 0 4px 20px rgba(0,0,0,0.2); } input#number-input { width: 50px; height: 35px; font-size: 18px; text-align: center; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; } select#difficulty { padding: 8px; font-size: 16px; border-radius: 4px; border: 1px solid #ccc; } </style> </head> <body> <h1>🎮 数独游戏</h1> <p class="subtitle">点击空白格输入数字,挑战你的逻辑思维!</p> <div class="controls"> <select id="difficulty"> <option value="easy">简单(40空格)</option> <option value="medium" selected>中等(50空格)</option> <option value="hard">困难(60空格)</option> </select> <button id="new-game-btn">新游戏</button> <button id="solve-btn">检查答案</button> <button id="answer-btn">显示答案</button> <button id="reset-btn">重置填写</button> </div> <div class="sudoku-board" id="board"></div> <!-- 输入模态框 --> <div class="modal" id="input-modal"> <div class="modal-content"> <p>请输入 1-9 的数字:</p> <input type="text" id="number-input" maxlength="1" autofocus /> </div> </div> <!-- 提示模态框 --> <div class="modal" id="alert-modal"> <div class="modal-content" id="alert-content"></div> </div> <script> let puzzle = []; let board = []; let solution = null; let selectedCell = null; const boardEl = document.getElementById("board"); const inputModal = document.getElementById("input-modal"); const numberInput = document.getElementById("number-input"); const alertModal = document.getElementById("alert-modal"); const alertContent = document.getElementById("alert-content"); // --- Step 1: 生成完整有效终盘 --- function generateFullSolution() { const board = Array(9).fill().map(() => Array(9).fill(0)); function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } function isValid(row, col, num) { for (let i = 0; i < 9; i++) { if (board[row][i] === num) return false; if (board[i][col] === num) return false; const br = Math.floor(row / 3) * 3 + Math.floor(i / 3); const bc = Math.floor(col / 3) * 3 + (i % 3); if (board[br][bc] === num) return false; } return true; } function backtrack() { for (let row = 0; row < 9; row++) { for (let col = 0; col < 9; col++) { if (board[row][col] === 0) { const nums = [1,2,3,4,5,6,7,8,9]; shuffle(nums); for (const num of nums) { if (isValid(row, col, num)) { board[row][col] = num; if (backtrack()) return true; board[row][col] = 0; } } return false; } } } return true; } backtrack(); return board; } // --- Step 2: 判断是否有唯一解 --- function hasUniqueSolution(puzzle) { let solutions = 0; function isValid(board, r, c, n) { for (let i = 0; i < 9; i++) { if (board[r][i] === n) return false; if (board[i][c] === n) return false; const br = Math.floor(r/3)*3 + Math.floor(i/3); const bc = Math.floor(c/3)*3 + i%3; if (board[br][bc] === n) return false; } return true; } function solve(board) { if (solutions >= 2) return; for (let r = 0; r < 9; r++) { for (let c = 0; c < 9; c++) { if (board[r][c] === 0) { for (let n = 1; n <= 9; n++) { if (isValid(board, r, c, n)) { board[r][c] = n; solve(board); board[r][c] = 0; } } return; } } } solutions++; } const testBoard = puzzle.map(row => [...row]); solve(testBoard); return solutions === 1; } // --- Step 3: 从终盘挖空生成谜题 --- function generatePuzzle(solution, difficulty = 'medium') { const counts = { easy: 40, medium: 50, hard: 60 }; const removeCount = counts[difficulty] || 50; let puzzle = solution.map(row => [...row]); const cells = []; for (let r = 0; r < 9; r++) { for (let c = 0; c < 9; c++) { cells.push([r, c]); } } // 打乱顺序 for (let i = cells.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [cells[i], cells[j]] = [cells[j], cells[i]]; } let removed = 0; for (const [r, c] of cells) { if (removed >= removeCount) break; const backup = puzzle[r][c]; puzzle[r][c] = 0; if (hasUniqueSolution(puzzle)) { removed++; } else { puzzle[r][c] = backup; } } return puzzle; } // --- 创建棋盘 UI --- function createBoard() { boardEl.innerHTML = ""; for (let row = 0; row < 9; row++) { for (let col = 0; col < 9; col++) { const cell = document.createElement("div"); cell.className = "cell"; cell.dataset.row = row; cell.dataset.col = col; if (puzzle[row][col] !== 0) { cell.textContent = puzzle[row][col]; cell.classList.add("fixed"); } else { cell.classList.add("editable"); cell.addEventListener("click", () => selectCell(cell)); } boardEl.appendChild(cell); } } } // --- 选择单元格 --- function selectCell(cell) { if (cell.classList.contains("fixed")) return; document.querySelectorAll(".cell").forEach(c => c.classList.remove("selected")); cell.classList.add("selected"); selectedCell = cell; inputModal.style.display = "flex"; numberInput.value = ""; setTimeout(() => numberInput.focus(), 100); } // --- 关闭模态框 --- function closeModal(modalEl) { modalEl.style.display = "none"; } // --- 显示提示信息 --- function showAlert(msg) { alertContent.innerHTML = `<p style="margin:10px 0;">${msg}</p><button onclick="closeModal(alertModal)">确定</button>`; alertModal.style.display = "flex"; } // --- 输入处理 --- numberInput.addEventListener("keydown", (e) => { if (e.key === "Enter") { const val = numberInput.value.trim(); if (/^[1-9]$/.test(val)) { const row = parseInt(selectedCell.dataset.row); const col = parseInt(selectedCell.dataset.col); board[row][col] = parseInt(val); selectedCell.textContent = val; selectedCell.classList.remove("error"); closeModal(inputModal); } else { numberInput.style.borderColor = "red"; setTimeout(() => numberInput.style.borderColor = "", 500); } } }); // --- 检查用户答案 --- function checkSolution() { if (!solution) { showAlert("❌ 谜题尚未生成!"); return; } let correct = true; let errors = 0; for (let row = 0; row < 9; row++) { for (let col = 0; col < 9; col++) { if (puzzle[row][col] === 0) { const cell = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`); const userVal = board[row][col]; if (userVal === 0 || userVal !== solution[row][col]) { cell.classList.add("error"); errors++; correct = false; } else { cell.classList.remove("error"); } } } } if (correct && errors === 0) { showAlert("🎉 恭喜!全部正确!"); } else if (errors > 0) { showAlert(`❌ 发现 ${errors} 处错误,请检查红色标记位置。`); } else { showAlert("仍有空白未填。"); } } // --- 显示答案 --- function showAnswer() { if (!solution) return; for (let row = 0; row < 9; row++) { for (let col = 0; col < 9; col++) { if (puzzle[row][col] === 0) { const cell = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`); cell.textContent = solution[row][col]; cell.classList.remove("error"); board[row][col] = solution[row][col]; } } } showAlert("✅ 正确答案已显示。"); } // --- 重置用户填写 --- function resetGame() { board = JSON.parse(JSON.stringify(puzzle)); createBoard(); // 重建保留固定值 showAlert("🔄 已清除所有输入内容。"); } // --- 生成新游戏 --- function newGame() { const difficulty = document.getElementById("difficulty").value; const full = generateFullSolution(); solution = full; puzzle = generatePuzzle(full, difficulty); board = JSON.parse(JSON.stringify(puzzle)); createBoard(); showAlert(`🆕 新游戏开始!难度:${difficulty}`); } // --- 初始化事件绑定 --- document.getElementById("new-game-btn").addEventListener("click", newGame); document.getElementById("solve-btn").addEventListener("click", checkSolution); document.getElementById("answer-btn").addEventListener("click", showAnswer); document.getElementById("reset-btn").addEventListener("click", resetGame); inputModal.addEventListener("click", e => { if (e.target === inputModal) closeModal(inputModal); }); alertModal.addEventListener("click", e => { if (e.target === alertModal) closeModal(alertModal); }); // 启动时生成一个默认游戏 window.onload = newGame; </script> </body> </html> ``` --- ### ✅ 功能一览 | 功能 | 是否支持 | |------|----------| | 自动生成合法唯一解数独 | ✅ | | 三种难度选择(简单/中等/困难) | ✅ | | 用户点击输入数字 | ✅ | | 输入验证(仅 1-9) | ✅ | | “检查答案”并标红错误 | ✅ | | “显示答案”覆盖当前内容 | ✅ | | “重置填写”清空用户输入 | ✅ | | “新游戏”按钮重新生成 | ✅ | | 响应式布局 & 视觉反馈 | ✅ | --- ### 🧪 使用方法 1. 将以上代码保存为 `sudoku.html` 2. 用浏览器打开文件 3. 自动开始一局“中等”难度游戏 4. 点击任意空白格输入数字 5. 可随时切换难度并点击“新游戏” --- ### 💡 技术亮点 - **真随机生成**:每次都是不同的终盘和谜题。 - **保证唯一解**:通过 `hasUniqueSolution()` 校验确保可玩性。 - **用户体验优化**: - 按钮颜色区分功能 - 输入框自动聚焦 - 错误高亮与提示信息友好 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值