類似 360 安全衛士的開關 UI:
background-position 切換開/關狀態CREATE TABLE `pro` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(50) NOT NULL COMMENT '功能標題',
`description` VARCHAR(200) NOT NULL COMMENT '功能說明',
`status` TINYINT(1) NOT NULL DEFAULT '0' COMMENT '0=關閉, 1=開啟',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
<?php
require_once 'connect.php';
$query = $mysqli->query("SELECT * FROM pro ORDER BY id ASC");
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>功能開關管理</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>系統功能開關</h1>
<?php while ($row = $query->fetch_assoc()): ?>
<div class="feature-item">
<div class="feature-header">
<h3><?= htmlspecialchars($row['title']) ?></h3>
<span class="toggle-switch"
data-id="<?= $row['id'] ?>"
data-status="<?= $row['status'] ?>"
role="switch"
aria-checked="<?= $row['status'] ? 'true' : 'false' ?>"
aria-label="<?= $row['status'] ? '關閉' : '開啟' ?> <?= htmlspecialchars($row['title']) ?>"
title="<?= $row['status'] ? '點擊關閉' : '點擊開啟' ?>"></span>
</div>
<p><?= htmlspecialchars($row['description']) ?></p>
</div>
<?php endwhile; ?>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="app.js"></script>
</body>
</html>
.container { max-width: 800px; margin: 40px auto; padding: 0 20px; }
.feature-item {
padding: 20px; border-bottom: 1px solid #eee;
position: relative; transition: background 0.2s;
}
.feature-item:hover { background: #fffbe6; }
.feature-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.feature-header h3 { font-size: 16px; font-weight: 600; color: #2c3e50; margin: 0; }
.feature-item p { color: #666; line-height: 1.6; margin: 0; }
/* 開關按鈕 - 使用單一圖片 Sprite */
.toggle-switch {
width: 64px; height: 32px;
background: url('switch-sprite.png') no-repeat;
cursor: pointer; border-radius: 16px;
transition: background-position 0.2s, box-shadow 0.2s;
flex-shrink: 0;
}
.toggle-switch.on { background-position: 0 0; box-shadow: inset 0 0 0 2px #27ae60; }
.toggle-switch.off { background-position: 0 -32px; box-shadow: inset 0 0 0 2px #ddd; }
.toggle-switch:focus { outline: 2px solid #3498db; outline-offset: 2px; }
.toggle-switch.loading { opacity: 0.6; pointer-events: none; }
/* Sprite 圖片說明:
寬 64px,高 64px
上半部 (0,0) = 開啟狀態 (綠色背景、滑塊在右)
下半部 (0,-32) = 關閉狀態 (灰色背景、滑塊在左)
*/
(function($) {
'use strict';
var $container = $('.container');
var apiUrl = 'action.php';
// 事件委派:動態新增項目也生效
$container.on('click', '.toggle-switch', function(e) {
e.preventDefault();
var $switch = $(this);
var id = $switch.data('id');
var currentStatus = $switch.data('status'); // 0 或 1
var newStatus = currentStatus === 1 ? 0 : 1;
var actionType = newStatus === 1 ? 'enable' : 'disable';
// UI 即時回饋:進入載入狀態
$switch.addClass('loading');
$.ajax({
url: apiUrl,
type: 'POST',
dataType: 'json',
data: { id: id, status: newStatus },
success: function(resp) {
if (resp.success) {
// 更新資料屬性與 ARIA
$switch.data('status', newStatus)
.attr('aria-checked', newStatus === 1)
.attr('title', newStatus === 1 ? '點擊關閉' : '點擊開啟')
.attr('aria-label', (newStatus === 1 ? '關閉' : '開啟') + ' 功能');
// 切換視覺類別
$switch.toggleClass('on off');
} else {
alert('操作失敗:' + (resp.message || '未知錯誤'));
// 可選:搖晃動畫提示失敗
$switch.addClass('shake');
setTimeout(() => $switch.removeClass('shake'), 500);
}
},
error: function(xhr) {
alert('請求異常:' + (xhr.responseJSON?.message || xhr.statusText));
},
complete: function() {
$switch.removeClass('loading');
}
});
});
// 滑鼠懸停列表高亮 (CSS :hover 已處理,JS 此處可擴充更複雜邏輯)
// $container.on('mouseenter mouseleave', '.feature-item', function(e) {
// $(this).toggleClass('hover', e.type === 'mouseenter');
// });
})(jQuery);
<?php
require_once 'connect.php';
header('Content-Type: application/json; charset=utf-8');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$status = isset($_POST['status']) ? (int)$_POST['status'] : 0;
if ($id <= 0 || ($status !== 0 && $status !== 1)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => '參數錯誤']);
exit;
}
// 使用 Prepared Statement 防 SQL 注入
$stmt = $mysqli->prepare("UPDATE pro SET status = ? WHERE id = ?");
$stmt->bind_param('ii', $status, $id);
$result = $stmt->execute();
if ($result) {
echo json_encode(['success' => true, 'status' => $status]);
} else {
http_response_code(500);
echo json_encode(['success' => false, 'message' => '資料庫更新失敗:' . $mysqli->error]);
}
$stmt->close();
$mysqli->close();
<?php
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
if ($mysqli->connect_errno) {
die('資料庫連線失敗:' . $mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4');
(int)、驗證狀態值htmlspecialchars() 防 XSSPATCH /api/features/{id},回傳標準 JSONversion 欄位防止覆蓋本範例展示了從資料庫設計、後端 API、前端樣式與互動邏輯的完整整合流程。核心技術點包括:CSS Sprite 開關動畫、AJAX 非同步更新、Prepared Statement 安全查詢、ARIA 無障礙屬性。這套模式廣泛應用於功能旗標、使用者偏好設定、內容審核狀態等場景,是全端開發者必備的基礎技能組合。