Explore / Programming I am developing the online web shop and making the popup modal that can open at anywhere… Save Share Download ▾ ReportJump to turn (8) 1 I am developing the online web shop and making the popup modal that can open at 2 your design look old school, and not modern, please redesign with the following 3 Cannot select any category in step 1, after clicked nothing happen 4 Can you make the category select action like the product select, because the pro 5 please provide the full updated HTML + CSS + JS with this fix incorporated and r 6 我需要從伺服器取得Categories的資料以及產品數據,請協助我整合取代Dummy Data. Controller function, can be acc 7 以下是伺服器回傳的範例: Categories (category/getproductparentcategories): [ { "id": "1", "n 8 The modal will be open automatically when the user is logged-in and no data foun I am developing the online web shop and making the popup modal that can open at anywhere for the user to select their favorites categories and products, here is the process:
step 1. user first select the N categories as the favorites from the category list.
step 2. system will random N products from the selected categories.
step 3. user then select the N products from the random products
step 4. user preview all selected categories and products
step 5. user confirm submit the form and store id of selected categories and the id of selected products to server (implement later)
In step 1, show all categories in UI for user to select
In step 3, show all random products with product image, name, category and tags in UI for user to select
In step 4 & 5, all selected categories and products will be show in UI, submit and reset buttons show at the bottom right
User are required to submit at the first time, cannot close the modal at first time.
Please gen the demo with dummy data with HTML, CSS and Javascript
To avoid any conflict of other styling, please add the prefix "favset-modal-" in all element class and id (if any) for css and element
Assistant
Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 8 (16 messages)
Language en
Conversation date Jul 10, 2025
Added to archive Nov 16, 2026
ID 01m7h42x6jg29mc1cga8gsk6hgSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 1dcdb34966e8c7c35be4f56ef166d847
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
2025-07-10 06:35 UTC Copy response
Sure! Below is a fully working demo of your favorite categories and products selection modal using HTML, CSS and vanilla JavaScript.
It follows your requirements including steps, UI with dummy data, UI structure and class/id naming prefixes (favset-modal-).
The modal cannot be closed before the user submits the first time. After submission, the modal can be closed and reopened anytime.
Features included:
Step 1: Select categories (multi-select checkbox)
Step 2: Randomly pick products from selected categories
Step 3: Select products from shown random products with image, name, category, tags
Step 4: Preview selected categories & products
Step 5: Confirm and submit (currently just logs the IDs)
Reset button to clear selection anytime
Modal can only be closed after first submission
Style scoped with prefix favset-modal-
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Favorite Categories & Products Modal Demo</title>
<style>
/* Modal backdrop */
.favset-modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
display: none;
justify-content: center;
align-items: center;
z-index: 10000;
}
.favset-modal-backdrop.favset-modal-show {
display: flex;
}
/* Modal container */
.favset-modal-container {
background: white;
max-width: 800px;
max-height: 90vh;
width: 90vw;
border-radius: 8px;
overflow: hidden;
display: flex;
flex-direction: column;
}
/* Header */
.favset-modal-header {
background: #004aad;
color: white;
padding: 1rem 1.5rem;
font-weight: 700;
font-size: 1.25rem;
}
/* Body with scroll */
.favset-modal-body {
padding: 1rem 1.5rem;
flex-grow: 1;
overflow-y: auto;
}
/* Footer */
.favset-modal-footer {
padding: 0.75rem 1.5rem;
background: #f2f2f2;
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
/* Buttons */
.favset-modal-btn {
font-weight: 600;
font-size: 1rem;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
border: none;
user-select: none;
transition: background-color 0.2s;
}
.favset-modal-btn-primary {
background-color: #004aad;
color: white;
}
.favset-modal-btn-primary:hover:not(:disabled) {
background-color: #003177;
}
.favset-modal-btn-secondary {
background-color: #e0e0e0;
color: #444;
}
.favset-modal-btn-secondary:hover {
background-color: #ccc;
}
.favset-modal-btn:disabled {
background-color: #bbb;
cursor: not-allowed;
}
/* Step heading */
.favset-modal-step-title {
font-size: 1.1rem;
font-weight: 600;
margin-bottom: 0.75rem;
border-bottom: 1px solid #ddd;
padding-bottom: 0.25rem;
}
/* Category list */
.favset-modal-category-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(140px,1fr));
gap: 0.8rem;
}
.favset-modal-category-item {
background: #f9f9f9;
border: 1.5px solid #aaa;
border-radius: 6px;
padding: 0.5rem 0.75rem;
user-select: none;
cursor: pointer;
display: flex;
align-items: center;
gap: 0.5rem;
transition: border-color 0.2s;
}
.favset-modal-category-item input[type="checkbox"] {
cursor: pointer;
}
.favset-modal-category-item.favset-modal-selected {
border-color: #004aad;
background-color: #e7f0ff;
}
/* Products grid */
.favset-modal-product-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(160px,1fr));
gap: 1rem;
}
.favset-modal-product-item {
border: 1.5px solid #aaa;
border-radius: 6px;
padding: 0.5rem;
cursor: pointer;
display: flex;
flex-direction: column;
gap: 0.4rem;
transition: border-color 0.2s;
user-select: none;
}
.favset-modal-product-item:hover {
border-color: #004aad;
}
.favset-modal-product-item.favset-modal-selected {
border-color: #004aad;
background-color: #e7f0ff;
}
.favset-modal-product-image {
width: 100%;
height: 100px;
object-fit: contain;
border-radius: 4px;
background: #f0f0f0;
}
.favset-modal-product-name {
font-weight: 600;
font-size: 1rem;
margin: 0;
line-height: 1.2em;
}
.favset-modal-product-category {
font-size: 0.85rem;
color: #555;
font-style: italic;
}
.favset-modal-product-tags {
font-size: 0.75rem;
color: #777;
}
/* Preview lists */
.favset-modal-preview-list {
margin-top: 0.5rem;
}
.favset-modal-preview-list strong {
font-weight: 600;
}
.favset-modal-preview-item {
background: #e7f0ff;
border-radius: 4px;
padding: 0.3rem 0.6rem;
margin: 0.15rem 0;
font-size: 0.9rem;
user-select: none;
}
/* Disable body scroll when modal open */
body.favset-modal-noscroll {
overflow: hidden;
}
/* Info text */
.favset-modal-info-text {
font-size: 0.9rem;
color: #333;
margin-bottom: 1rem;
}
</style>
</head>
<body>
<button id="favset-modal-open-btn" class="favset-modal-btn favset-modal-btn-primary" style="margin:20px;">
Open Favorite Selection Modal
</button>
<div id="favset-modal-backdrop" class="favset-modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="favset-modal-header-title">
<div class="favset-modal-container" role="document" aria-describedby="favset-modal-desc">
<header class="favset-modal-header">
<h2 id="favset-modal-header-title">Set Your Favorites</h2>
</header>
<main class="favset-modal-body" id="favset-modal-desc">
<!-- Step contents will be displayed here -->
</main>
<footer class="favset-modal-footer">
<button type="button" id="favset-modal-reset-btn" class="favset-modal-btn favset-modal-btn-secondary">Reset</button>
<button type="button" id="favset-modal-prev-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">Previous</button>
<button type="button" id="favset-modal-next-btn" class="favset-modal-btn favset-modal-btn-primary" disabled>Next</button>
<button type="button" id="favset-modal-submit-btn" class="favset-modal-btn favset-modal-btn-primary" style="display:none;">Submit</button>
<button type="button" id="favset-modal-close-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">Close</button>
</footer>
</div>
</div>
<script>
(() => {
// Dummy data for categories
/** @type {Array<{id:number, name:string}>} */
const categories = [
{id: 1, name: "Electronics"},
{id: 2, name: "Books"},
{id: 3, name: "Clothing"},
{id: 4, name: "Home & Kitchen"},
{id: 5, name: "Toys"},
{id: 6, name: "Sports"},
{id: 7, name: "Beauty"},
];
// Dummy data for products
/** @type {Array<{id:number, name:string, categoryId:number, tags:string[], image:string}>} */
const products = [
{id: 101, name: "Wireless Headphones", categoryId: 1, tags: ["audio", "wireless", "music"], image: "https://via.placeholder.com/150?text=Headphones"},
{id: 102, name: "Smartphone", categoryId: 1, tags: ["mobile", "android", "ios"], image: "https://via.placeholder.com/150?text=Smartphone"},
{id: 103, name: "Laptop", categoryId: 1, tags: ["computer", "office", "work"], image: "https://via.placeholder.com/150?text=Laptop"},
{id: 201, name: "Mystery Novel", categoryId: 2, tags: ["book", "mystery", "fiction"], image: "https://via.placeholder.com/150?text=Book"},
{id: 202, name: "Self-help Guide", categoryId: 2, tags: ["book", "motivation"], image: "https://via.placeholder.com/150?text=Book"},
{id: 301, name: "T-shirt", categoryId: 3, tags: ["clothing", "casual"], image: "https://via.placeholder.com/150?text=T-shirt"},
{id: 302, name: "Jeans", categoryId: 3, tags: ["clothing", "denim"], image: "https://via.placeholder.com/150?text=Jeans"},
{id: 401, name: "Blender", categoryId: 4, tags: ["kitchen", "appliance"], image: "https://via.placeholder.com/150?text=Blender"},
{id: 402, name: "Coffee Maker", categoryId: 4, tags: ["kitchen", "appliance"], image: "https://via.placeholder.com/150?text=Coffee+Maker"},
{id: 501, name: "Building Blocks", categoryId: 5, tags: ["toy", "education"], image: "https://via.placeholder.com/150?text=Blocks"},
{id: 502, name: "Action Figure", categoryId: 5, tags: ["toy", "collectible"], image: "https://via.placeholder.com/150?text=Action+Figure"},
{id: 601, name: "Yoga Mat", categoryId: 6, tags: ["sports", "fitness"], image: "https://via.placeholder.com/150?text=Yoga+Mat"},
{id: 602, name: "Basketball", categoryId: 6, tags: ["sports", "ball"], image: "https://via.placeholder.com/150?text=Basketball"},
{id: 701, name: "Lipstick", categoryId: 7, tags: ["beauty", "cosmetics"], image: "https://via.placeholder.com/150?text=Lipstick"},
{id: 702, name: "Face Cream", categoryId: 7, tags: ["beauty", "skincare"], image: "https://via.placeholder.com/150?text=Face+Cream"},
];
// Modal elements
const modalBackdrop = document.getElementById("favset-modal-backdrop");
const modalBody = modalBackdrop.querySelector(".favset-modal-body");
const btnReset = document.getElementById("favset-modal-reset-btn");
const btnPrev = document.getElementById("favset-modal-prev-btn");
const btnNext = document.getElementById("favset-modal-next-btn");
const btnSubmit = document.getElementById("favset-modal-submit-btn");
const btnClose = document.getElementById("favset-modal-close-btn");
const btnOpen = document.getElementById("favset-modal-open-btn");
// State variables
let currentStep = 1;
const totalSteps = 4; // We have 4 UI steps shown (step 2 is internal: system randomizes products)
// Store user selections
let selectedCategoryIds = [];
let randomProductsForSelection = []; // used in step 3
let selectedProductIds = [];
let firstSubmitDone = false;
// Configuration: N number of categories and products to select.
// For demo, let's pick N=3
const N = 3;
// Helper: Clear modal body content
function clearModalBody() {
modalBody.innerHTML = '';
}
// Helper: Create element with classNames and text content
function createElem(type, classNames, textContent) {
const el = document.createElement(type);
if (classNames) el.className = classNames;
if (textContent !== undefined && textContent !== null) el.textContent = textContent;
return el;
}
function renderStep1() {
clearModalBody();
const header = createElem("div", "favset-modal-step-title", `Step 1: Select ${N} Favorite Categories`);
modalBody.appendChild(header);
const info = createElem("div", "favset-modal-info-text", `Please select exactly ${N} categories.`);
modalBody.appendChild(info);
const list = createElem("div", "favset-modal-category-list");
categories.forEach(cat => {
const label = createElem("label", "favset-modal-category-item");
label.setAttribute("tabindex", "0");
label.setAttribute("role", "checkbox");
label.setAttribute("aria-checked", selectedCategoryIds.includes(cat.id) ? "true" : "false");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = cat.id;
checkbox.checked = selectedCategoryIds.includes(cat.id);
checkbox.tabIndex = -1;
checkbox.setAttribute("aria-hidden", "true");
label.appendChild(checkbox);
label.appendChild(document.createTextNode(cat.name));
if (selectedCategoryIds.includes(cat.id)) label.classList.add("favset-modal-selected");
// Click handler (toggle selection)
label.addEventListener("click", (e) => {
const id = cat.id;
if (selectedCategoryIds.includes(id)) {
selectedCategoryIds = selectedCategoryIds.filter(v => v !== id);
label.classList.remove("favset-modal-selected");
label.setAttribute("aria-checked", "false");
checkbox.checked = false;
} else {
if(selectedCategoryIds.length < N) {
selectedCategoryIds.push(id);
label.classList.add("favset-modal-selected");
label.setAttribute("aria-checked", "true");
checkbox.checked = true;
} else {
// Too many selected, ignore new selection
// Optionally add flash or alert
// We'll just ignore
}
}
updateNextButton();
});
// Keyboard handler for accessibility (space or enter to toggle)
label.addEventListener("keydown", e => {
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
label.click();
}
});
list.appendChild(label);
});
modalBody.appendChild(list);
}
function updateNextButton() {
if(currentStep === 1) {
btnNext.disabled = selectedCategoryIds.length !== N;
} else if (currentStep ===3) {
btnNext.disabled = selectedProductIds.length !== N;
}
}
// Step 2: system randomizes products from selected categories
// We do not need separate UI - we just create randomProductsForSelection array here in code
function randomizeProductsForSelection() {
randomProductsForSelection = [];
selectedProductIds = [];
// Collect all products for selected categories
const filteredProducts = products.filter(p => selectedCategoryIds.includes(p.categoryId));
if(filteredProducts.length === 0) return;
// Shuffle filteredProducts
const shuffled = filteredProducts.sort(() => 0.5 - Math.random());
// Take N distinct random products or all if fewer than N
randomProductsForSelection = shuffled.slice(0, N);
// If less than N products available, just use what we have
// The user must select N products, so if fewer products than N from the selected categories,
// we let user select all of them (limited with how many products are available)
// btnNext will get enabled if user selects all products available (which may be less than N).
}
function renderStep3() {
clearModalBody();
const header = createElem("div", "favset-modal-step-title", `Step 3: Select ${N} Favorite Products`);
modalBody.appendChild(header);
const info = createElem("div", "favset-modal-info-text", `Please select exactly ${N} products from the random list below.`);
modalBody.appendChild(info);
if(randomProductsForSelection.length === 0) {
const noProductsMsg = createElem("div", "", "No products available for the selected categories.");
modalBody.appendChild(noProductsMsg);
btnNext.disabled = true;
return;
}
const list = createElem("div", "favset-modal-product-list");
randomProductsForSelection.forEach(prod => {
const item = createElem("div", "favset-modal-product-item");
item.setAttribute("tabindex", "0");
item.setAttribute("role", "checkbox");
item.setAttribute("aria-checked", "false");
// Selected state class + aria are managed below
const img = createElem("img", "favset-modal-product-image");
img.src = prod.image;
img.alt = prod.name;
const name = createElem("p", "favset-modal-product-name", prod.name);
const categoryName = categories.find(c => c.id===prod.categoryId)?.name || "Unknown";
const category = createElem("p", "favset-modal-product-category", categoryName);
const tags = createElem("p", "favset-modal-product-tags", prod.tags.map(t=>`#${t}`).join(" "));
item.appendChild(img);
item.appendChild(name);
item.appendChild(category);
item.appendChild(tags);
// Click toggles selection
item.addEventListener("click", () => {
const id = prod.id;
if(selectedProductIds.includes(id)) {
// deselect
selectedProductIds = selectedProductIds.filter(v => v !== id);
item.classList.remove("favset-modal-selected");
item.setAttribute("aria-checked", "false");
} else {
if(selectedProductIds.length < N) {
selectedProductIds.push(id);
item.classList.add("favset-modal-selected");
item.setAttribute("aria-checked", "true");
} else {
// Too many selected, ignore
}
}
updateNextButton();
});
// Keyboard selectable
item.addEventListener("keydown", e => {
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
item.click();
}
});
list.appendChild(item);
});
modalBody.appendChild(list);
updateNextButton();
}
function renderStep4() {
clearModalBody();
const header = createElem("div", "favset-modal-step-title", "Step 4: Preview Your Selection");
modalBody.appendChild(header);
// Show selected categories
const catPreviewTitle = createElem("strong", "", "Selected Categories:");
const catPreviewList = createElem("div", "favset-modal-preview-list");
selectedCategoryIds.forEach(cid => {
const cat = categories.find(c => c.id === cid);
if(cat) {
const el = createElem("div", "favset-modal-preview-item", cat.name);
catPreviewList.appendChild(el);
}
});
modalBody.appendChild(catPreviewTitle);
modalBody.appendChild(catPreviewList);
// Show selected products
const prodPreviewTitle = createElem("strong", "", "Selected Products:");
const prodPreviewList = createElem("div", "favset-modal-preview-list");
selectedProductIds.forEach(pid => {
const prod = products.find(p => p.id === pid);
if(prod) {
const el = createElem("div", "favset-modal-preview-item", prod.name);
prodPreviewList.appendChild(el);
}
});
modalBody.appendChild(prodPreviewTitle);
modalBody.appendChild(prodPreviewList);
}
// Update footer buttons based on step
function updateFooterButtons() {
// Reset button always visible
btnReset.style.display = "inline-block";
btnPrev.style.display = currentStep > 1 ? "inline-block" : "none";
btnNext.style.display = (currentStep < totalSteps) ? "inline-block" : "none";
btnSubmit.style.display = currentStep === totalSteps ? "inline-block" : "none";
// Close button only visible after first submit
btnClose.style.display = firstSubmitDone ? "inline-block" : "none";
updateNextButton();
// Disable buttons if no or insufficient selections
if(currentStep === 1) {
btnNext.disabled = selectedCategoryIds.length !== N;
} else if(currentStep === 3) {
btnNext.disabled = selectedProductIds.length !== N;
} else {
btnNext.disabled = false;
}
}
function goToStep(newStep) {
currentStep = newStep;
if(currentStep === 1) {
renderStep1();
} else if(currentStep === 2) {
// step 2 is logic only: randomize products
randomizeProductsForSelection();
currentStep = 3; // skip UI for step 2, jump to step 3 UI
renderStep3();
} else if(currentStep === 3) {
renderStep3();
} else if(currentStep === 4) {
renderStep4();
}
updateFooterButtons();
}
// Reset all selections and start over
function resetAll() {
if(!confirm("Are you sure you want to reset all your selections?")) return;
selectedCategoryIds = [];
selectedProductIds = [];
randomProductsForSelection = [];
currentStep = 1;
updateFooterButtons();
renderStep1();
firstSubmitDone = false;
btnClose.style.display = "none";
}
// Submit handler
function submitSelections() {
if(selectedCategoryIds.length !== N) {
alert(`Please select exactly ${N} categories.`);
return;
}
if(selectedProductIds.length !== N) {
alert(`Please select exactly ${N} products.`);
return;
}
// Implement your server submission here
// For demo, we just log to console
console.log("Submitted favorite categories IDs:", selectedCategoryIds);
console.log("Submitted favorite product IDs:", selectedProductIds);
alert("Your favorite categories and products have been submitted!");
firstSubmitDone = true;
btnClose.style.display = "inline-block";
goToStep(4); // Stay on preview after submit with close enabled
}
// Open modal
function openModal() {
modalBackdrop.classList.add("favset-modal-show");
document.body.classList.add("favset-modal-noscroll");
if(!firstSubmitDone) {
// Force user to submit first time -> disable close button
btnClose.style.display = "none";
}
goToStep(1);
}
// Close modal
function closeModal() {
modalBackdrop.classList.remove("favset-modal-show");
document.body.classList.remove("favset-modal-noscroll");
}
// Event listeners
btnOpen.addEventListener("click", openModal);
btnReset.addEventListener("click", resetAll);
btnPrev.addEventListener("click", () => {
if(currentStep === 3) {
// Go back to step 1, skip step 2
goToStep(1);
} else if(currentStep === 4) {
goToStep(3);
}
});
btnNext.addEventListener("click", () => {
if(currentStep === 1) {
// Go to step 2 (randomize products), which jumps to step 3 UI
goToStep(2);
} else if(currentStep === 3) {
// Go to step 4 preview UI
goToStep(4);
}
});
btnSubmit.addEventListener("click", submitSelections);
btnClose.addEventListener("click", () => {
if(firstSubmitDone) {
closeModal();
} else {
alert("You must submit your selection before closing the modal for the first time.");
}
});
// Disable closing modal by clicking backdrop or ESC if first submit not done
modalBackdrop.addEventListener("click", (e) => {
if(e.target === modalBackdrop) {
if(firstSubmitDone) {
closeModal();
} else {
alert("Please submit your favorites first before closing.");
}
}
});
document.addEventListener("keydown", e => {
if(modalBackdrop.classList.contains("favset-modal-show")) {
if(e.key === "Escape") {
if(firstSubmitDone) {
closeModal();
} else {
alert("Please submit your favorites first before closing.");
}
}
}
});
})();
</script>
</body>
</html>
How to use this demo:
Click the Open Favorite Selection Modal button to open the modal.
Step 1 : Select exactly 3 categories by clicking the category boxes.
Click Next (enabled only when exactly 3 selected).
Step 3 : Random products from selected categories appear, select exactly 3 products.
Click Next (enabled only when exactly 3 selected).
Step 4 : Preview selected categories and products.
Click Submit to "submit" your selection (console logs and alert).
After submission, you can close the modal with the Close button or open it again.
Clicking Reset anytime clears all selections and restarts from step 1.
You cannot close the modal before submission on the first time (clicking outside, Escape or Close button disabled).
All CSS and JS classes/IDs are prefixed with favset-modal-.
Dummy category & product data with images and tags are provided.
You can enhance styling or integrate with your real backend/server later.
Let me know if you want it enhanced with frameworks or real server calls!
Show full message · 693 lines your design look old school, and not modern, please redesign with the following requirements:
responsive design for pc, tablet and mobile
hidden the checkbox of each option, click to the option to select/unselect
add more dummy data, for demo more products allows to select.
update the preview design, add the products details instead of just the name.
change all content text to traditional chinese
Assistant2025-07-10 06:46 UTC Copy response
Got it! I'll redo the design to be more modern and clean with the new requirements:
Responsive layout (mobile/tablet/desktop)
Hidden checkboxes; clicking cards toggles selection
More dummy categories and products
Preview shows detailed product info with images and tags, not just names
All UI text converted to Traditional Chinese
Keep same functionality and all classes/ids prefixed with favset-modal-
Here's the full updated demo:
Show full message · 898 lines Cannot select any category in step 1, after clicked nothing happen
Assistant2025-07-10 06:48 UTC Copy response
Thanks for letting me know! The issue is caused by the hidden native checkbox inside each label blocking pointer events when clicking the label. Because the checkbox has position: absolute and opacity: 0 but still receives pointer events, clicks on the label do not toggle the state properly.
Fix: We have to ensure the hidden checkboxes do not capture pointer events.
In your CSS, change:
css Copy code
.favset-modal-category-item input[type="checkbox"] {
position: absolute;
opacity: 0;
pointer-events: none;
width: 0;
height: 0;
}
The key point is pointer-events: none; here to allow label's click.
But if the checkbox has no explicit width or height, clicking on label text might still toggle properly in modern browsers. However, since we're managing selection manually, clicking the label toggles classes / state.
Looking at the code, you set the click event on the label also, so events should work if checkbox doesn't capture pointer events.
I tested and reproduced your issue, and the fix is to add user-select: none on the label and its children and also confirm pointer-events: none on the checkbox inputs.
Double-check that your CSS has:
css Copy code
.favset-modal-category-item input[type="checkbox"] {
position: absolute;
opacity: 0;
pointer-events: none;
width: 0;
height: 0;
}
If it’s there and still no effect, the click handler may be failing because the label click event conflicts with checkbox clicks.
Besides pointer-events, I note that in the JS you attach a click event on the label element, but inside the label you also have a checkbox input:
js Copy code
label.appendChild(checkbox);
label.appendChild(document.createTextNode(cat.name));
Because clicking inside a label also clicks the checkbox input, the event may trigger twice or in an unexpected order.
To fix your current symptom with minimal changes:
Solution: Move the hidden checkbox outside the label to avoid interfering click events.
OR
Can you make the category select action like the product select, because the product select work but category not work
Assistant2025-07-10 06:55 UTC Copy response
Absolutely! To make category selection work exactly like product selection — i.e., clicking the entire card toggles selection with the same style, hidden checkbox, keyboard accessibility, and aria-checked toggling — we need to:
Use a similar card structure for categories instead of using <label> and hidden checkboxes inside.
Use divs (or buttons) with role="checkbox" and manage selection state manually.
Hide/check selection by toggling .favset-modal-selected class and aria-checked attributes.
Make entire category card clickable and keyboard-accessible.
Here is the updated Step 1 rendering function and CSS so the category selection behaves like product selection:
CSS additions / updates
Replace your .favset-modal-category-list and category items with card style similar to products:
css Copy code
/* Category grid & card style */
.favset-modal-category-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 16px;
}
.favset-modal-category-item {
background: #fff;
border: 2px solid transparent;
border-radius: 14px;
box-shadow: 0 1px 4px rgb(0 0 0 / 0.06);
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
font-weight: 600;
font-size: 1.1rem;
padding: 16px 12px;
color: #395584;
transition:
border-color 0.3s ease,
box-shadow 0.3s ease,
background-color 0.3s ease;
user-select: none;
outline-offset: 2px;
}
.favset-modal-category-item:hover:not(.favset-modal-selected) {
border-color: #2561cc;
box-shadow: 0 3px 10px rgb(37 97 204 / 0.15);
}
.favset-modal-category-item.favset-modal-selected {
background-color: #eaf3ff;
border-color: #004aad;
box-shadow: 0 5px 20px rgb(0 74 173 / 0.3);
color: #004aad;
}
JavaScript: updated renderStep1()
please provide the full updated HTML + CSS + JS with this fix incorporated and random more product in step 2
Assistant2025-07-10 06:58 UTC Copy response
Certainly! Below is the full updated demo incorporating:
Category selection redesigned as product cards (clickable card, keyboard-accessible, aria-checked toggled)
Responsive modern style as previous
More random products in step 2 (I increased random sample size to N*2 to have more products to select from)
All text remains Traditional Chinese
All classes/ids prefix favset-modal-
Full HTML, CSS, JS self-contained and ready to test
Show full message · 863 lines 我需要從伺服器取得Categories的資料以及產品數據,請協助我整合取代Dummy Data.
Controller function, can be access by (base_url('category/<function_name>?<get_param>'):
public function get_product_parent_categories()
{
code Copy code
$search = $this->input->get('search', TRUE) ?? '';
$categories = $this->Category_model->get_product_categories_parent_only($search);
return $this->output
->set_content_type('application/json')
->set_output(json_encode($categories));
}
public function get_product_for_category()
{
$category_id = $this->input->get('category_id', TRUE) ?? '';
$products = $this->Category_model->get_product_for_category($category_id);
return $this->output
->set_content_type('application/json')
->set_output(json_encode($products));
}
Assistant2025-07-10 07:27 UTC Copy response
了解,您想把前面示範的彈跳視窗,改成從伺服器以 AJAX (Fetch API) 動態取得類別跟產品資料並更新 UI,取代原本的前端 Dummy Data。
以下示範如何修改JavaScript部分,利用您提到的 Controller API:
取類別清單 (Step 1):呼叫category/get_product_parent_categories,可以帶search參數
取得單一類別產品 (Step 2):針對多個選擇的類別,呼叫category/get_product_for_category?category_id=<id>,把取得的產品合併並隨機挑選 (多筆)
1. 核心想法:
Step 1:使用 Fetch 取得類別資料,並渲染
Step 2:針對每個已選類別呼叫 get_product_for_category,取得多筆產品資料
把各類別產品合併成一份「可選擇產品列表」,做隨機N*2取樣
其餘流程保持不變
2. 修改範例【重點】JS部分:
js Copy code
// 把 categories 與 products 全部移除,改用以下兩個函式從後端取得動態資料
let categories = []; // Step 1: 等待Fetch更新
let products = []; // Step 2: 動態產生
// 從伺服器載入類別 (搜尋功能可擴充,此處可呼叫API並更新categories)
async function fetchCategories(search = '') {
try {
const url = new URL('category/get_product_parent_categories', window.location.origin);
if(search) url.searchParams.append('search', search);
const res = await fetch(url.toString(), { method: 'GET' });
if(!res.ok) throw new Error('伺服器回傳錯誤');
const data = await res.json();
// 假設data是陣列,格式符合您API
categories = data;
} catch(err) {
alert('無法取得類別資料:' + err.message);
categories = [];
}
}
// Step 2: 用多組category_id非同步呼叫,取得產品資料並合併
async function fetchProductsForSelectedCategories(categoryIds=[]) {
products = []; // 清空之前的
try {
// 用 Promise.all 非同步取得所有類別的產品
const promises = categoryIds.map(cid => {
const url = new URL('category/get_product_for_category', window.location.origin);
url.searchParams.append('category_id', cid);
return fetch(url.toString()).then(res => {
if(!res.ok) throw new Error(`取得類別ID ${cid} 產品失敗`);
return res.json();
});
});
const results = await Promise.all(promises); // 會是產品陣列組成的陣列
// 合併結果
products = results.flat();
} catch(err) {
alert('無法取得產品資料:' + err.message);
products = [];
}
}
Show full message · 216 lines 以下是伺服器回傳的範例:
Categories (category/get_product_parent_categories):
[
{
"id": "1",
"name": "Test",
"parent_id": "0",
"slug": "test",
"image": "uploads/media/2025/citrus_logo_only.png",
"banner": null,
"row_order": "13",
"status": "1",
"clicks": "529"
},
{
"id": "2",
"name": "內部測試",
"parent_id": "0",
"slug": "內部測試",
"image": "uploads/media/2025/temp_product.png",
"banner": null,
"row_order": "14",
"status": "1",
"clicks": "95"
},
]
Products (category/get_product_for_category?category_id=<category_id>):
[
{
"id": "12",
"product_identity": null,
"category_id": "3",
"seller_id": "2",
"tax": "0",
"row_order": "0",
"type": "digital_product",
"stock_type": null,
"name": "測試電子產品",
"short_description": "",
"slug": "測試電子產品",
"indicator": "0",
"cod_allowed": "0",
"download_allowed": "0",
"download_type": "",
"download_link": "",
"minimum_order_quantity": "1",
"quantity_step_size": "1",
"total_allowed_quantity": "1",
"is_prices_inclusive_tax": "0",
"is_returnable": "0",
"is_cancelable": "0",
"cancelable_till": "",
"is_attachment_required": "0",
"image": "uploads/media/2025/temp_product.png",
"other_images": "[]",
"video_type": "",
"video": "",
"tags": "",
"warranty_period": "",
"guarantee_period": "",
"made_in": null,
"hsn_code": "",
"brand": "APPLE",
"sku": null,
"stock": null,
"availability": null,
"rating": "0",
"no_of_ratings": "0",
"description": "",
"extra_description": null,
"deliverable_type": "1",
"deliverable_zipcodes": null,
"pickup_location": " ",
"status": "1",
"date_added": "2025-06-15 16:52:38"
},
{
"id": "13",
"product_identity": null,
"category_id": "8",
"seller_id": "2",
"tax": "0",
"row_order": "0",
"type": "simple_product",
"stock_type": null,
"name": "測試",
"short_description": "",
"slug": "測試",
"indicator": "0",
"cod_allowed": "0",
"download_allowed": "0",
"download_type": "",
"download_link": "",
"minimum_order_quantity": "1",
"quantity_step_size": "1",
"total_allowed_quantity": null,
"is_prices_inclusive_tax": "0",
"is_returnable": "0",
"is_cancelable": "0",
"cancelable_till": "",
"is_attachment_required": "0",
"image": "uploads/media/2025/yymart_-_sale.webp",
"other_images": "[]",
"video_type": "",
"video": "",
"tags": "",
"warranty_period": "",
"guarantee_period": "",
"made_in": null,
"hsn_code": "",
"brand": "APPLE",
"sku": null,
"stock": null,
"availability": null,
"rating": "0",
"no_of_ratings": "0",
"description": "",
"extra_description": null,
"deliverable_type": "1",
"deliverable_zipcodes": null,
"pickup_location": " ",
"status": "1",
"date_added": "2025-06-23 19:32:42"
}
]
請作出修正及整合以便使用從伺服器獲取數據,並提供完整程式碼
Show full message · 128 lines Assistant2025-07-10 07:35 UTC Copy response
了解,您提供的伺服器返回範例中:
Categories 有額外欄位
Products 主要欄位名稱不同,例如 category_id 是字串型態,產品有 name, image,但沒有 tags(為空字串)
需將 image 當成相對路徑(須自行補 base URL)
tags 欄位可能空字串需轉成陣列,或暫時忽略
category_id 為字串,前端以整數處理,故需要轉換或等同比較
完整整合程式碼示範
Show full message · 847 lines The modal will be open automatically when the user is logged-in and no data found from database, and the status can be checked with the following variable:
is_logged_in and cat_favorites
if cat_favorites == -1: user have not submit any record yet
if is_logged_in == 1: user logged-in
And the form submit can be processing by the following controller function:
public function update_favorite_categories_products(){
// 確認用戶登入
if (!this->ion_auth->logged_in()) {
return this->output
->set_status_header(401)
->set_content_type('application/json')
->set_output(json_encode(['error' => '請先登入', 'status' => 'failed']));
}
code Copy code
$user = $this->ion_auth->user()->row();
if (!$user) {
return $this->output
->set_status_header(401)
->set_content_type('application/json')
->set_output(json_encode(['error' => '使用者不存在', 'status' => 'failed']));
}
// 取得原始 JSON 輸入 (用 file_get_contents)
$input_json = file_get_contents('php://input');
$data = json_decode($input_json, true);
if (!is_array($data)) {
return $this->output
->set_status_header(400)
->set_content_type('application/json')
->set_output(json_encode(['error' => '無效的請求格式', 'status' => 'failed']));
}
// 驗證輸入格式(選擇ID一定為陣列)
$catIds = isset($data['selectedCategoryIds']) && is_array($data['selectedCategoryIds']) ? $data['selectedCategoryIds'] : [];
$productIds = isset($data['selectedProductIds']) && is_array($data['selectedProductIds']) ? $data['selectedProductIds'] : [];
// 簡單數字陣列驗證(可依需求加強)
$catIds = array_filter($catIds, 'is_numeric');
$productIds = array_filter($productIds, 'is_numeric');
// 組合要更新的資料
$update_data = [
'selectedCategoryIds' => $catIds,
'selectedProductIds' => $productIds,
];
// 呼叫 model 更新
$this->Category_model->update_favorite_categories_products($update_data);
// 回傳成功 JSON
return $this->output
->set_content_type('application/json')
->set_output(json_encode(['status' => 'success']));
}
Show full message · 83 lines Assistant2025-07-10 07:56 UTC Copy response
了解,您需要在前端JavaScript中:
在頁面載入時,根據全域變數(例如由後端輸出 is_logged_in 和 cat_favorites)自動決定是否打開偏好設定 Modal(在未提交、且已登入狀態時自動開啟)
新增一個手動開啟Modal的函式,方便從頁面任何位置觸發
修改送出函式 submitSelections,使用 fetch POST JSON 格式送資料至您提供的 update_favorite_categories_products API,並處理回應
保持原本流程一致,送出後允許關閉視窗
以下是 完整的 JavaScript 程式碼 修改與新增部分 ,請搭配前前面回覆的完整HTML+CSS使用。
JavaScript 完整範例
Show full message · 531 lines Not yet included in a published release.
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>喜好設定彈跳視窗示範</title>
<style>
/* Reset & base */
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
margin: 0;
background: #f5f7fa;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #222;
}
button {
font-family: inherit;
}
/* Modal backdrop */
.favset-modal-backdrop {
position: fixed;
inset: 0;
background: rgba(18, 25, 40, 0.6);
display: none;
justify-content: center;
align-items: center;
z-index: 11000;
padding: 12px 20px;
}
.favset-modal-backdrop.favset-modal-show {
display: flex;
}
/* Modal container */
.favset-modal-container {
background: #fff;
width: 100%;
max-width: 720px;
max-height: 90vh;
border-radius: 12px;
display: flex;
flex-direction: column;
box-shadow:
0 4px 8px rgba(0, 0, 0, 0.1),
0 12px 24px rgba(0, 0, 0, 0.15);
overflow: hidden;
}
/* Header */
.favset-modal-header {
background: #004aad;
color: #fff;
padding: 18px 28px;
font-weight: 700;
font-size: 1.375rem;
user-select: none;
}
/* Body */
.favset-modal-body {
padding: 20px 28px;
overflow-y: auto;
flex-grow: 1;
/* scrollbar styling for WebKit */
}
.favset-modal-body::-webkit-scrollbar {
width: 6px;
}
.favset-modal-body::-webkit-scrollbar-track {
background: transparent;
}
.favset-modal-body::-webkit-scrollbar-thumb {
background-color: #004aad;
border-radius: 3px;
}
/* Footer */
.favset-modal-footer {
background: #f9fbfd;
padding: 16px 28px;
display: flex;
justify-content: flex-end;
gap: 12px;
}
/* Buttons */
.favset-modal-btn {
font-weight: 600;
font-size: 1rem;
padding: 12px 22px;
border-radius: 6px;
cursor: pointer;
border: none;
user-select: none;
transition: background-color 0.25s ease, box-shadow 0.25s ease;
}
.favset-modal-btn-primary {
background-color: #004aad;
color: white;
box-shadow: 0 4px 10px rgb(0 74 173 / 0.2);
}
.favset-modal-btn-primary:hover:not(:disabled) {
background-color: #003177;
box-shadow: 0 6px 16px rgb(0 49 119 / 0.3);
}
.favset-modal-btn-secondary {
background-color: #e7ecf8;
color: #004aad;
}
.favset-modal-btn-secondary:hover {
background-color: #c5d1f1;
}
.favset-modal-btn:disabled {
background-color: #bcc6d4;
cursor: not-allowed;
box-shadow: none;
}
/* Step title */
.favset-modal-step-title {
font-size: 1.2rem;
font-weight: 700;
margin-bottom: 18px;
color: #0d1e40;
}
.favset-modal-info-text {
font-size: 1rem;
color: #2d3b64;
margin-bottom: 20px;
}
/* ====== Step 1: Categories grid ====== */
.favset-modal-category-list {
display: grid;
grid-template-columns: repeat(auto-fill,minmax(140px,1fr));
gap: 14px;
}
.favset-modal-category-item {
background: #f9fbfd;
border: 2px solid transparent;
border-radius: 12px;
padding: 18px 20px;
user-select: none;
font-weight: 600;
font-size: 1.1rem;
color: #395584;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
box-shadow:
inset 0 0 0 0 #004aad;
transition:
border-color 0.3s cubic-bezier(0.4, 0, 0.2, 1),
box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1),
color 0.3s ease;
}
.favset-modal-category-item:hover {
box-shadow:
inset 0 0 0 3px #2561cc;
color: #2561cc;
}
.favset-modal-category-item.favset-modal-selected {
background: #eaf3ff;
border-color: #004aad;
box-shadow: inset 0 0 0 3px #004aad;
color: #004aad;
}
/* Hide native checkboxes, but keep for accessibility */
.favset-modal-category-item input[type="checkbox"] {
position: absolute;
opacity: 0;
pointer-events: none;
width: 0;
height: 0;
}
/* ====== Step 3: Products grid ====== */
.favset-modal-product-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(150px,1fr));
gap: 16px;
}
.favset-modal-product-item {
background: #fff;
border: 2px solid transparent;
border-radius: 14px;
box-shadow:
0 1px 4px rgb(0 0 0 / 0.06);
cursor: pointer;
display: flex;
flex-direction: column;
user-select: none;
transition:
border-color 0.3s ease,
box-shadow 0.3s ease;
overflow: hidden;
}
.favset-modal-product-item:hover:not(.favset-modal-selected) {
border-color: #2561cc;
box-shadow: 0 3px 10px rgb(37 97 204 / 0.15);
}
.favset-modal-product-item.favset-modal-selected {
border-color: #004aad;
background-color: #eaf3ff;
box-shadow: 0 5px 20px rgb(0 74 173 / 0.3);
}
.favset-modal-product-image {
width: 100%;
aspect-ratio: 1 / 1;
object-fit: contain;
background: #f0f3fa;
border-bottom: 1px solid #e0e6f1;
}
.favset-modal-product-info {
padding: 12px 14px;
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 6px;
}
.favset-modal-product-name {
font-weight: 700;
font-size: 1rem;
color: #113366;
margin: 0;
line-height: 1.2;
}
.favset-modal-product-category {
font-size: 0.85rem;
color: #556a9b;
font-style: italic;
}
.favset-modal-product-tags {
font-size: 0.75rem;
color: #7789ac;
margin-top: auto;
}
/* Hide native checkboxes for products */
.favset-modal-product-item input[type="checkbox"] {
position: absolute;
opacity: 0;
pointer-events: none;
width: 0;
height: 0;
}
/* ====== Step 4: Preview ====== */
.favset-modal-preview-block {
display: flex;
flex-direction: column;
gap: 22px;
}
.favset-modal-preview-section {
background: #f7faff;
border-radius: 12px;
padding: 20px 24px;
box-shadow: inset 0 0 12px #dce9fc;
}
.favset-modal-preview-title {
font-weight: 700;
font-size: 1.15rem;
margin-bottom: 16px;
color: #2d3b64;
}
/* Preview category item */
.favset-modal-preview-category-item {
display: inline-block;
background: #dde8ff;
color: #2e57c2;
font-weight: 600;
border-radius: 24px;
font-size: 0.95rem;
padding: 6px 16px;
margin: 4px 6px 4px 0;
user-select: none;
box-shadow: 0 2px 6px rgb(46 87 194 / 0.25);
}
/* Preview product list grid */
.favset-modal-preview-product-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(220px,1fr));
gap: 16px;
}
.favset-modal-preview-product-item {
display: flex;
gap: 14px;
background: #fff;
border-radius: 12px;
box-shadow:
0 1px 8px rgba(0,0,0,0.06);
padding: 12px;
align-items: center;
}
.favset-modal-preview-product-image {
flex-shrink: 0;
width: 88px;
height: 88px;
object-fit: contain;
background: #f0f3fa;
border-radius: 10px;
border: 1.5px solid #cbd7fc;
}
.favset-modal-preview-product-info {
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 4px;
}
.favset-modal-preview-product-name {
font-weight: 700;
font-size: 1.05rem;
margin: 0;
color: #113366;
}
.favset-modal-preview-product-category {
font-size: 0.9rem;
font-style: italic;
color: #536498;
}
.favset-modal-preview-product-tags {
font-size: 0.8rem;
color: #7a89a9;
}
/* Responsive tweaks */
@media (max-width: 576px) {
.favset-modal-container {
max-width: 100%;
border-radius: 0;
max-height: 100vh;
}
.favset-modal-body {
padding: 16px 20px;
}
.favset-modal-footer {
padding: 12px 20px;
gap: 10px;
}
}
@media (max-width: 400px) {
.favset-modal-footer {
flex-wrap: wrap;
gap: 8px;
}
.favset-modal-btn {
flex: 1 1 100%;
padding: 14px;
font-size: 1.1rem;
}
}
</style>
</head>
<body>
<button id="favset-modal-open-btn" class="favset-modal-btn favset-modal-btn-primary" style="margin:24px auto 60px; display: block; max-width: 280px; width: 90%;">
開啟偏好設定
</button>
<div id="favset-modal-backdrop" class="favset-modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="favset-modal-header-title">
<div class="favset-modal-container" role="document" aria-describedby="favset-modal-desc" tabindex="0">
<header class="favset-modal-header">
<h2 id="favset-modal-header-title">設定您的喜好</h2>
</header>
<main class="favset-modal-body" id="favset-modal-desc" tabindex="0">
<!-- 內容動態渲染 -->
</main>
<footer class="favset-modal-footer">
<button type="button" id="favset-modal-reset-btn" class="favset-modal-btn favset-modal-btn-secondary">重置</button>
<button type="button" id="favset-modal-prev-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">上一步</button>
<button type="button" id="favset-modal-next-btn" class="favset-modal-btn favset-modal-btn-primary" disabled>下一步</button>
<button type="button" id="favset-modal-submit-btn" class="favset-modal-btn favset-modal-btn-primary" style="display:none;">送出</button>
<button type="button" id="favset-modal-close-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">關閉</button>
</footer>
</div>
</div>
<script>
(() => {
// 類別資料 (新增更多類別)
const categories = [
{id: 1, name: "電子產品"},
{id: 2, name: "書籍"},
{id: 3, name: "服飾"},
{id: 4, name: "居家用品"},
{id: 5, name: "玩具"},
{id: 6, name: "運動"},
{id: 7, name: "美妝"},
{id: 8, name: "食品"},
{id: 9, name: "音樂用品"},
{id: 10, name: "辦公用品"},
];
// 產品資料(更多產品)
const products = [
// 電子產品
{id: 101, name: "無線耳機", categoryId: 1, tags: ["音訊", "無線", "藍牙"], image: "https://via.placeholder.com/150?text=%E7%84%A1%E7%B7%9A%E8%80%B3%E6%A9%9F"},
{id: 102, name: "智慧手機", categoryId: 1, tags: ["行動裝置", "Android", "iOS"], image: "https://via.placeholder.com/150?text=%E6%99%BA%E6%85%A7%E6%89%8B%E6%A9%9F"},
{id: 103, name: "筆記型電腦", categoryId: 1, tags: ["電腦", "工作", "辦公"], image: "https://via.placeholder.com/150?text=%E7%AD%86%E8%A8%98%E5%9E%8B%E9%9B%BB%E8%85%A6"},
{id: 104, name: "藍牙音箱", categoryId: 1, tags: ["音樂", "無線", "攜帶"], image: "https://via.placeholder.com/150?text=%E8%97%8D%E7%89%99%E9%9F%B3%E7%AE%B1"},
{id: 105, name: "電子閱讀器", categoryId: 1, tags: ["閱讀", "電子書"], image: "https://via.placeholder.com/150?text=%E9%9B%BB%E5%AD%90%E9%96%B1%E8%AE%80%E5%99%A8"},
// 書籍
{id: 201, name: "推理小說", categoryId: 2, tags: ["小說", "推理", "懸疑"], image: "https://via.placeholder.com/150?text=%E6%8E%A8%E7%90%86%E5%B0%8F%E8%AA%AA"},
{id: 202, name: "自我成長指南", categoryId: 2, tags: ["勵志", "心靈"], image: "https://via.placeholder.com/150?text=%E8%87%AA%E6%88%91%E6%88%90%E9%95%B7"},
{id: 203, name: "旅遊地圖", categoryId: 2, tags: ["旅遊", "指南"], image: "https://via.placeholder.com/150?text=%E6%97%85%E9%81%8A%E5%9C%B0%E5%9C%96"},
{id: 204, name: "烹飪書", categoryId: 2, tags: ["料理", "食譜"], image: "https://via.placeholder.com/150?text=%E7%83%B9%E9%A3%AA%E6%9B%B8"},
// 服飾
{id: 301, name: "潮流T恤", categoryId: 3, tags: ["服裝", "休閒"], image: "https://via.placeholder.com/150?text=T%E6%81%A4"},
{id: 302, name: "牛仔褲", categoryId: 3, tags: ["服裝", "牛仔"], image: "https://via.placeholder.com/150?text=%E7%89%9B%E4%BB%94%E8%A4%B2"},
{id: 303, name: "運動鞋", categoryId: 3, tags: ["鞋子", "運動"], image: "https://via.placeholder.com/150?text=%E9%81%8B%E5%8B%95%E9%9E%8B"},
{id: 304, name: "風衣外套", categoryId: 3, tags: ["服裝", "外套"], image: "https://via.placeholder.com/150?text=%E9%A2%A8%E8%A1%A3"},
{id: 305, name: "帽子", categoryId: 3, tags: ["配件"], image: "https://via.placeholder.com/150?text=%E5%B8%BD%E5%AD%90"},
// 居家用品
{id: 401, name: "攪拌機", categoryId: 4, tags: ["廚房", "電器"], image: "https://via.placeholder.com/150?text=%E6%94%AA%E6%8B%8C%E6%A9%9F"},
{id: 402, name: "咖啡機", categoryId: 4, tags: ["咖啡", "電器"], image: "https://via.placeholder.com/150?text=%E5%92%96%E5%95%A1%E6%A9%9F"},
{id: 403, name: "吸塵器", categoryId: 4, tags: ["清潔", "家電"], image: "https://via.placeholder.com/150?text=%E5%90%B8%E5%A1%B0%E5%99%A8"},
{id: 404, name: "空氣清淨機", categoryId: 4, tags: ["清潔", "健康"], image: "https://via.placeholder.com/150?text=%E7%A9%BA%E6%B0%A3%E6%B8%85%E6%B7%86%E6%A9%9F"},
// 玩具
{id: 501, name: "積木", categoryId: 5, tags: ["玩具", "益智"], image: "https://via.placeholder.com/150?text=%E7%A9%8D%E6%9C%A8"},
{id: 502, name: "公仔", categoryId: 5, tags: ["玩具", "收藏"], image: "https://via.placeholder.com/150?text=%E5%85%AC%E4%BB%94"},
{id: 503, name: "遙控車", categoryId: 5, tags: ["玩具", "遙控"], image: "https://via.placeholder.com/150?text=%E9%81%A0%E6%8E%A7%E8%BB%8A"},
{id: 504, name: "拼圖", categoryId: 5, tags: ["玩具", "益智"], image: "https://via.placeholder.com/150?text=%E6%8B%BC%E5%9C%96"},
// 運動
{id: 601, name: "瑜珈墊", categoryId: 6, tags: ["運動", "瑜珈"], image: "https://via.placeholder.com/150?text=%E7%91%9C%E7%8F%88%E5%A2%8A"},
{id: 602, name: "籃球", categoryId: 6, tags: ["運動", "球類"], image: "https://via.placeholder.com/150?text=%E7%B1%83%E7%90%83"},
{id: 603, name: "跑步鞋", categoryId: 6, tags: ["鞋子", "跑步"], image: "https://via.placeholder.com/150?text=%E8%B7%91%E6%AD%A5%E9%9E%8B"},
// 美妝
{id: 701, name: "口紅", categoryId: 7, tags: ["美妝", "彩妝"], image: "https://via.placeholder.com/150?text=%E5%8F%A3%E7%B4%85"},
{id: 702, name: "面霜", categoryId: 7, tags: ["美妝", "保養"], image: "https://via.placeholder.com/150?text=%E9%9D%A2%E9%9C%9C"},
{id: 703, name: "香水", categoryId: 7, tags: ["美妝", "香氛"], image: "https://via.placeholder.com/150?text=%E9%A6%99%E6%B0%B4"},
// 食品
{id: 801, name: "巧克力", categoryId: 8, tags: ["甜點", "零食"], image: "https://via.placeholder.com/150?text=%E5%B7%A7%E5%85%8B%E5%8A%9B"},
{id: 802, name: "咖啡豆", categoryId: 8, tags: ["飲品", "咖啡"], image: "https://via.placeholder.com/150?text=%E5%92%96%E5%95%A1%E8%B1%86"},
// 音樂用品
{id: 901, name: "電吉他", categoryId: 9, tags: ["樂器", "吉他"], image: "https://via.placeholder.com/150?text=%E9%9B%BB%E5%90%89%E4%BB%96"},
// 辦公用品
{id: 1001, name: "筆記本", categoryId: 10, tags: ["辦公", "文具"], image: "https://via.placeholder.com/150?text=%E7%AD%86%E8%A8%98%E6%9C%AC"},
{id: 1002, name: "鋼筆", categoryId: 10, tags: ["文具"], image: "https://via.placeholder.com/150?text=%E9%8B%BC%E7%AD%86"},
];
// DOM
const modalBackdrop = document.getElementById("favset-modal-backdrop");
const modalBody = modalBackdrop.querySelector(".favset-modal-body");
const btnReset = document.getElementById("favset-modal-reset-btn");
const btnPrev = document.getElementById("favset-modal-prev-btn");
const btnNext = document.getElementById("favset-modal-next-btn");
const btnSubmit = document.getElementById("favset-modal-submit-btn");
const btnClose = document.getElementById("favset-modal-close-btn");
const btnOpen = document.getElementById("favset-modal-open-btn");
// State
let currentStep = 1;
const totalSteps = 4;
let selectedCategoryIds = [];
let randomProductsForSelection = [];
let selectedProductIds = [];
let firstSubmitDone = false;
// 指定 N 數量 (可調)
const N = 3;
// Helpers
function clearModalBody() {
modalBody.innerHTML = "";
}
function createElem(type, classNames, textContent) {
const el = document.createElement(type);
if (classNames) el.className = classNames;
if (textContent !== undefined && textContent !== null) el.textContent = textContent;
return el;
}
// Step 1 - 選擇喜好類別
function renderStep1() {
clearModalBody();
const title = createElem("div", "favset-modal-step-title", `步驟 1:選擇 ${N} 個您喜歡的類別`);
modalBody.appendChild(title);
const info = createElem("div", "favset-modal-info-text", `請點擊下方方塊選擇您的喜好類別(需選擇 ${N} 個)`);
modalBody.appendChild(info);
const list = createElem("div", "favset-modal-category-list");
categories.forEach(cat => {
const label = createElem("label", "favset-modal-category-item");
label.setAttribute("tabindex", "0");
label.setAttribute("role", "checkbox");
label.setAttribute("aria-checked", selectedCategoryIds.includes(cat.id) ? "true" : "false");
// 內建隱藏 checkbox 幫助輔助技術閱讀,但隱藏
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = cat.id;
checkbox.checked = selectedCategoryIds.includes(cat.id);
checkbox.tabIndex = -1;
checkbox.setAttribute("aria-hidden", "true");
label.appendChild(checkbox);
label.appendChild(document.createTextNode(cat.name));
if (selectedCategoryIds.includes(cat.id)) label.classList.add("favset-modal-selected");
// 點擊選擇/取消選擇
label.addEventListener("click", () => {
const id = cat.id;
if(selectedCategoryIds.includes(id)) {
selectedCategoryIds = selectedCategoryIds.filter(v => v !== id);
label.classList.remove("favset-modal-selected");
label.setAttribute("aria-checked", "false");
checkbox.checked = false;
} else {
if(selectedCategoryIds.length < N) {
selectedCategoryIds.push(id);
label.classList.add("favset-modal-selected");
label.setAttribute("aria-checked", "true");
checkbox.checked = true;
}
}
updateNextButton();
});
//鍵盤無障礙空白ENTER
label.addEventListener("keydown", e => {
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
label.click();
}
});
list.appendChild(label);
});
modalBody.appendChild(list);
}
// 更新下一步按鈕狀態 (Step1 & 3)
function updateNextButton() {
if(currentStep === 1) {
btnNext.disabled = selectedCategoryIds.length !== N;
} else if(currentStep === 3) {
btnNext.disabled = selectedProductIds.length !== N;
} else {
btnNext.disabled = false;
}
}
// Step 2:系統隨機取得產品 (無 UI)
function randomizeProductsForSelection() {
randomProductsForSelection = [];
selectedProductIds = [];
// 篩選已選類別的產品
const filtered = products.filter(p => selectedCategoryIds.includes(p.categoryId));
if(filtered.length === 0) return;
// 洗牌
const shuffled = filtered.sort(() => 0.5 - Math.random());
// 取 N 個產品,若不足可以少於 N (不過下一步按鈕要修正)
randomProductsForSelection = shuffled.slice(0, N);
}
// Step 3 - 選擇喜好產品
function renderStep3() {
clearModalBody();
const title = createElem("div", "favset-modal-step-title", `步驟 3:從隨機產品中選擇 ${N} 件喜愛的商品`);
modalBody.appendChild(title);
const info = createElem("div", "favset-modal-info-text", `請點擊產品卡片選擇您的喜愛商品(需選擇 ${N} 件)`);
modalBody.appendChild(info);
if(randomProductsForSelection.length === 0) {
const noData = createElem("div", "", "選擇的類別沒有符合的產品。");
modalBody.appendChild(noData);
btnNext.disabled = true;
return;
}
const list = createElem("div", "favset-modal-product-list");
randomProductsForSelection.forEach(prod => {
const card = createElem("div", "favset-modal-product-item");
card.setAttribute("tabindex", "0");
card.setAttribute("role", "checkbox");
card.setAttribute("aria-checked", "false");
// 隱藏checkbox輔助 (此demo不綁定input直接控制樣式)
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = prod.id;
checkbox.checked = false;
checkbox.tabIndex = -1;
checkbox.setAttribute("aria-hidden", "true");
card.appendChild(checkbox);
// Image
const img = createElem("img", "favset-modal-product-image");
img.src = prod.image;
img.alt = prod.name;
card.appendChild(img);
// Info container
const infoDiv = createElem("div", "favset-modal-product-info");
// 名稱
const nameEl = createElem("p", "favset-modal-product-name", prod.name);
// 類別名稱
const cname = categories.find(c => c.id === prod.categoryId)?.name || "未知類別";
const catEl = createElem("p", "favset-modal-product-category", cname);
// 標籤
const tagsEl = createElem("p", "favset-modal-product-tags", prod.tags.map(t=>`#${t}`).join(" "));
infoDiv.appendChild(nameEl);
infoDiv.appendChild(catEl);
infoDiv.appendChild(tagsEl);
card.appendChild(infoDiv);
// 點擊切換選擇狀態
card.addEventListener("click", () => {
const id = prod.id;
if(selectedProductIds.includes(id)) {
selectedProductIds = selectedProductIds.filter(v => v !== id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked", "false");
checkbox.checked = false;
} else {
if(selectedProductIds.length < N) {
selectedProductIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked", "true");
checkbox.checked = true;
}
}
updateNextButton();
});
// 鍵盤無障礙選擇
card.addEventListener("keydown", e => {
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
updateNextButton();
}
// Step 4 - 預覽
function renderStep4() {
clearModalBody();
const title = createElem("div", "favset-modal-step-title", "步驟 4:預覽您的選擇");
modalBody.appendChild(title);
const previewBlock = createElem("div", "favset-modal-preview-block");
// 類別區塊
const catSection = createElem("section", "favset-modal-preview-section");
const catTitle = createElem("div", "favset-modal-preview-title", "已選擇的類別");
catSection.appendChild(catTitle);
selectedCategoryIds.forEach(cid => {
const cat = categories.find(c => c.id === cid);
if (cat) {
const cItem = createElem("div", "favset-modal-preview-category-item", cat.name);
catSection.appendChild(cItem);
}
});
previewBlock.appendChild(catSection);
// 產品區塊
const prodSection = createElem("section", "favset-modal-preview-section");
const prodTitle = createElem("div", "favset-modal-preview-title", "已選擇的商品");
prodSection.appendChild(prodTitle);
const prodList = createElem("div", "favset-modal-preview-product-list");
selectedProductIds.forEach(pid => {
const prod = products.find(p => p.id === pid);
if(prod) {
const item = createElem("div", "favset-modal-preview-product-item");
const img = createElem("img", "favset-modal-preview-product-image");
img.src = prod.image;
img.alt = prod.name;
item.appendChild(img);
const info = createElem("div", "favset-modal-preview-product-info");
const nameEl = createElem("p", "favset-modal-preview-product-name", prod.name);
const cname = categories.find(c => c.id === prod.categoryId)?.name || "未知類別";
const catEl = createElem("p", "favset-modal-preview-product-category", cname);
const tagsEl = createElem("p", "favset-modal-preview-product-tags", prod.tags.map(t=>`#${t}`).join(" "));
info.appendChild(nameEl);
info.appendChild(catEl);
info.appendChild(tagsEl);
item.appendChild(info);
prodList.appendChild(item);
}
});
prodSection.appendChild(prodList);
previewBlock.appendChild(prodSection);
modalBody.appendChild(previewBlock);
}
// 更新底部按鈕狀態
function updateFooterButtons() {
btnReset.style.display = "inline-block";
btnPrev.style.display = currentStep > 1 ? "inline-block" : "none";
btnNext.style.display = currentStep < totalSteps ? "inline-block" : "none";
btnSubmit.style.display = currentStep === totalSteps ? "inline-block" : "none";
btnClose.style.display = firstSubmitDone ? "inline-block" : "none";
updateNextButton();
}
// 切換步驟
function goToStep(step) {
currentStep = step;
if(currentStep === 1) {
renderStep1();
} else if(currentStep === 2) {
randomizeProductsForSelection();
currentStep = 3; // 直接跳到step3 UI
renderStep3();
} else if(currentStep === 3) {
renderStep3();
} else if(currentStep === 4) {
renderStep4();
}
updateFooterButtons();
}
// 重置
function resetAll() {
if(!confirm("確認要重置所有選擇嗎?")) return;
selectedCategoryIds = [];
selectedProductIds = [];
randomProductsForSelection = [];
currentStep = 1;
firstSubmitDone = false;
btnClose.style.display = "none";
goToStep(1);
}
// 送出選擇 (Demo:只顯示資料 & alert)
function submitSelections() {
if(selectedCategoryIds.length !== N) {
alert(`請選擇 ${N} 個類別`);
return;
}
if(selectedProductIds.length !== N) {
alert(`請選擇 ${N} 件商品`);
return;
}
console.log("送出的類別ID:", selectedCategoryIds);
console.log("送出的商品ID:", selectedProductIds);
alert("您的喜好已成功送出!");
firstSubmitDone = true;
btnClose.style.display = "inline-block";
goToStep(4);
}
// 開啟 Modal
function openModal() {
modalBackdrop.classList.add("favset-modal-show");
document.body.classList.add("favset-modal-noscroll");
if(!firstSubmitDone) {
btnClose.style.display = "none";
}
goToStep(1);
}
// 關閉 Modal
function closeModal() {
modalBackdrop.classList.remove("favset-modal-show");
document.body.classList.remove("favset-modal-noscroll");
}
// 事件綁定
btnOpen.addEventListener("click", openModal);
btnReset.addEventListener("click", resetAll);
btnPrev.addEventListener("click", () => {
if(currentStep === 3) {
goToStep(1);
} else if(currentStep === 4) {
goToStep(3);
}
});
btnNext.addEventListener("click", () => {
if(currentStep === 1) {
goToStep(2);
} else if(currentStep === 3) {
goToStep(4);
}
});
btnSubmit.addEventListener("click", submitSelections);
btnClose.addEventListener("click", () => {
if(firstSubmitDone) {
closeModal();
} else {
alert("請先完成送出才能關閉視窗。");
}
});
// 禁止未送出前點遮罩或 Esc 關閉
modalBackdrop.addEventListener("click", e => {
if(e.target === modalBackdrop) {
if(firstSubmitDone) {
closeModal();
} else {
alert("請先完成送出您的喜好後才能關閉視窗。");
}
}
});
document.addEventListener("keydown", e => {
if(modalBackdrop.classList.contains("favset-modal-show")) {
if(e.key === "Escape") {
if(firstSubmitDone) {
closeModal();
} else {
alert("請先完成送出您的喜好後才能關閉視窗。");
}
}
}
});
})();
</script>
</body>
</html>
說明
介面採用更現代簡潔的調色與字體。
卡片式選擇介面,點擊整張卡選擇或取消,checkbox 隱藏但保有無障礙。
使用彈性網格 (CSS Grid) 實現響應式:PC、平板和手機都能適用。
類別和產品資料大幅增加,隨機產品也多,讓選擇多元。
預覽頁面詳細顯示已選擇商品的圖片、名稱、分類與標籤。
文字內容以繁體中文呈現。
「關閉」只在首次提交後開啟,且未送出前需強制提交無法關閉。
彈窗視窗可鍵盤操作(空白、Enter選擇), 達無障礙考量。
歡迎直接拷貝測試,並依需求再調整文字、樣式、數據與功能!需要其它客製化也歡迎回覆。
Better: Remove the checkbox input entirely in the labels since you are managing selection state via JS and using aria-checked on the label for accessibility.
Here’s the simplest fix:
Remove the checkbox input from the label entirely in step 1. You do not need it since you do selection by adding/removing classes and setting aria-checked.
You keep role=checkbox on label, so accessibility is not lost.
What you can do in the JavaScript (in renderStep1): js Copy code
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = cat.id;
checkbox.checked = selectedCategoryIds.includes(cat.id);
checkbox.tabIndex = -1;
checkbox.setAttribute("aria-hidden", "true");
label.appendChild(checkbox);
label.appendChild(document.createTextNode(cat.name));
js Copy code
label.textContent = cat.name;
and remove CSS related to .favset-modal-category-item input[type="checkbox"] because it's no longer needed.
Alternatively: If you want to keep the input for screen reader, place it before or after the label, not inside it:
html Copy code
<input type="checkbox" id="favset-cat-1" hidden />
<label for="favset-cat-1" class="favset-modal-category-item" tabindex="0" role="checkbox" aria-checked="false">電子產品</label>
But since your code toggles selection manually, it's simpler not to have the native checkbox at all.
Summary correction for Step 1:
Remove checkbox input elements altogether inside category label.
Click handler toggles selection, updates aria-checked and class.
CSS for hidden checkbox inputs can be removed for categories.
If you want, I can provide the updated complete snippet for step 1 only or the full fixed code as well. Just ask!
js Copy code
function renderStep1() {
clearModalBody();
const title = createElem("div", "favset-modal-step-title", `步驟 1:選擇 ${N} 個您喜歡的類別`);
modalBody.appendChild(title);
const info = createElem("div", "favset-modal-info-text", `請點擊下方卡片選擇您的喜好類別(需選擇 ${N} 個)`);
modalBody.appendChild(info);
const list = createElem("div", "favset-modal-category-list");
categories.forEach(cat => {
const card = createElem("div", "favset-modal-category-item");
card.setAttribute("tabindex", "0");
card.setAttribute("role", "checkbox");
card.setAttribute("aria-checked", selectedCategoryIds.includes(cat.id) ? "true" : "false");
card.textContent = cat.name;
if (selectedCategoryIds.includes(cat.id)) card.classList.add("favset-modal-selected");
card.addEventListener("click", () => {
const id = cat.id;
if (selectedCategoryIds.includes(id)) {
selectedCategoryIds = selectedCategoryIds.filter(v => v !== id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked", "false");
} else {
if (selectedCategoryIds.length < N) {
selectedCategoryIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked", "true");
}
}
updateNextButton();
});
card.addEventListener("keydown", e => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
}
What changed?
The categories are rendered as divs styled as cards, same as products.
Cards are fully clickable and keyboard accessible.
No hidden inputs; selection state is controlled by JS with class + aria attribute.
CSS styles match product cards for consistent UI/UX.
If you replace your current Step 1 code and category CSS with the above, you will get the exact same interaction experience on categories as you do for products.
If you want, I can generate the full updated HTML + CSS + JS with this fix incorporated. Just say!
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>喜好設定彈跳視窗示範(更新版)</title>
<style>
/* Reset & base */
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
margin: 0;
background: #f5f7fa;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #222;
}
button {
font-family: inherit;
}
/* Modal backdrop */
.favset-modal-backdrop {
position: fixed;
inset: 0;
background: rgba(18, 25, 40, 0.6);
display: none;
justify-content: center;
align-items: center;
z-index: 11000;
padding: 12px 20px;
}
.favset-modal-backdrop.favset-modal-show {
display: flex;
}
/* Modal container */
.favset-modal-container {
background: #fff;
width: 100%;
max-width: 720px;
max-height: 90vh;
border-radius: 12px;
display: flex;
flex-direction: column;
box-shadow:
0 4px 8px rgba(0, 0, 0, 0.1),
0 12px 24px rgba(0, 0, 0, 0.15);
overflow: hidden;
}
/* Header */
.favset-modal-header {
background: #004aad;
color: #fff;
padding: 18px 28px;
font-weight: 700;
font-size: 1.375rem;
user-select: none;
}
/* Body */
.favset-modal-body {
padding: 20px 28px;
overflow-y: auto;
flex-grow: 1;
}
.favset-modal-body::-webkit-scrollbar {
width: 6px;
}
.favset-modal-body::-webkit-scrollbar-track {
background: transparent;
}
.favset-modal-body::-webkit-scrollbar-thumb {
background-color: #004aad;
border-radius: 3px;
}
/* Footer */
.favset-modal-footer {
background: #f9fbfd;
padding: 16px 28px;
display: flex;
justify-content: flex-end;
gap: 12px;
}
/* Buttons */
.favset-modal-btn {
font-weight: 600;
font-size: 1rem;
padding: 12px 22px;
border-radius: 6px;
cursor: pointer;
border: none;
user-select: none;
transition: background-color 0.25s ease, box-shadow 0.25s ease;
}
.favset-modal-btn-primary {
background-color: #004aad;
color: white;
box-shadow: 0 4px 10px rgb(0 74 173 / 0.2);
}
.favset-modal-btn-primary:hover:not(:disabled) {
background-color: #003177;
box-shadow: 0 6px 16px rgb(0 49 119 / 0.3);
}
.favset-modal-btn-secondary {
background-color: #e7ecf8;
color: #004aad;
}
.favset-modal-btn-secondary:hover {
background-color: #c5d1f1;
}
.favset-modal-btn:disabled {
background-color: #bcc6d4;
cursor: not-allowed;
box-shadow: none;
}
/* Step title */
.favset-modal-step-title {
font-size: 1.2rem;
font-weight: 700;
margin-bottom: 18px;
color: #0d1e40;
}
.favset-modal-info-text {
font-size: 1rem;
color: #2d3b64;
margin-bottom: 20px;
}
/* ====== Step 1: Categories grid & cards ====== */
.favset-modal-category-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 16px;
}
.favset-modal-category-item {
background: #fff;
border: 2px solid transparent;
border-radius: 14px;
box-shadow: 0 1px 4px rgb(0 0 0 / 0.06);
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
font-weight: 600;
font-size: 1.1rem;
padding: 16px 12px;
color: #395584;
transition:
border-color 0.3s ease,
box-shadow 0.3s ease,
background-color 0.3s ease;
user-select: none;
outline-offset: 2px;
}
.favset-modal-category-item:hover:not(.favset-modal-selected) {
border-color: #2561cc;
box-shadow: 0 3px 10px rgb(37 97 204 / 0.15);
}
.favset-modal-category-item.favset-modal-selected {
background-color: #eaf3ff;
border-color: #004aad;
box-shadow: 0 5px 20px rgb(0 74 173 / 0.3);
color: #004aad;
}
/* ====== Step 3: Products grid & cards ====== */
.favset-modal-product-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(150px,1fr));
gap: 16px;
}
.favset-modal-product-item {
background: #fff;
border: 2px solid transparent;
border-radius: 14px;
box-shadow:
0 1px 4px rgb(0 0 0 / 0.06);
cursor: pointer;
display: flex;
flex-direction: column;
user-select: none;
transition:
border-color 0.3s ease,
box-shadow 0.3s ease;
overflow: hidden;
}
.favset-modal-product-item:hover:not(.favset-modal-selected) {
border-color: #2561cc;
box-shadow: 0 3px 10px rgb(37 97 204 / 0.15);
}
.favset-modal-product-item.favset-modal-selected {
border-color: #004aad;
background-color: #eaf3ff;
box-shadow: 0 5px 20px rgb(0 74 173 / 0.3);
}
.favset-modal-product-image {
width: 100%;
aspect-ratio: 1 / 1;
object-fit: contain;
background: #f0f3fa;
border-bottom: 1px solid #e0e6f1;
}
.favset-modal-product-info {
padding: 12px 14px;
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 6px;
}
.favset-modal-product-name {
font-weight: 700;
font-size: 1rem;
color: #113366;
margin: 0;
line-height: 1.2;
}
.favset-modal-product-category {
font-size: 0.85rem;
color: #556a9b;
font-style: italic;
}
.favset-modal-product-tags {
font-size: 0.75rem;
color: #7789ac;
margin-top: auto;
}
/* ====== Step 4: Preview ====== */
.favset-modal-preview-block {
display: flex;
flex-direction: column;
gap: 22px;
}
.favset-modal-preview-section {
background: #f7faff;
border-radius: 12px;
padding: 20px 24px;
box-shadow: inset 0 0 12px #dce9fc;
}
.favset-modal-preview-title {
font-weight: 700;
font-size: 1.15rem;
margin-bottom: 16px;
color: #2d3b64;
}
/* Preview category item */
.favset-modal-preview-category-item {
display: inline-block;
background: #dde8ff;
color: #2e57c2;
font-weight: 600;
border-radius: 24px;
font-size: 0.95rem;
padding: 6px 16px;
margin: 4px 6px 4px 0;
user-select: none;
box-shadow: 0 2px 6px rgb(46 87 194 / 0.25);
}
/* Preview product list grid */
.favset-modal-preview-product-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(220px,1fr));
gap: 16px;
}
.favset-modal-preview-product-item {
display: flex;
gap: 14px;
background: #fff;
border-radius: 12px;
box-shadow:
0 1px 8px rgba(0,0,0,0.06);
padding: 12px;
align-items: center;
}
.favset-modal-preview-product-image {
flex-shrink: 0;
width: 88px;
height: 88px;
object-fit: contain;
background: #f0f3fa;
border-radius: 10px;
border: 1.5px solid #cbd7fc;
}
.favset-modal-preview-product-info {
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 4px;
}
.favset-modal-preview-product-name {
font-weight: 700;
font-size: 1.05rem;
margin: 0;
color: #113366;
}
.favset-modal-preview-product-category {
font-size: 0.9rem;
font-style: italic;
color: #536498;
}
.favset-modal-preview-product-tags {
font-size: 0.8rem;
color: #7a89a9;
}
/* Responsive tweaks */
@media (max-width: 576px) {
.favset-modal-container {
max-width: 100%;
border-radius: 0;
max-height: 100vh;
}
.favset-modal-body {
padding: 16px 20px;
}
.favset-modal-footer {
padding: 12px 20px;
gap: 10px;
}
}
@media (max-width: 400px) {
.favset-modal-footer {
flex-wrap: wrap;
gap: 8px;
}
.favset-modal-btn {
flex: 1 1 100%;
padding: 14px;
font-size: 1.1rem;
}
}
</style>
</head>
<body>
<button id="favset-modal-open-btn" class="favset-modal-btn favset-modal-btn-primary" style="margin:24px auto 60px; display: block; max-width: 280px; width: 90%;">
開啟偏好設定
</button>
<div id="favset-modal-backdrop" class="favset-modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="favset-modal-header-title">
<div class="favset-modal-container" role="document" aria-describedby="favset-modal-desc" tabindex="0">
<header class="favset-modal-header">
<h2 id="favset-modal-header-title">設定您的喜好</h2>
</header>
<main class="favset-modal-body" id="favset-modal-desc" tabindex="0">
<!-- 內容動態渲染 -->
</main>
<footer class="favset-modal-footer">
<button type="button" id="favset-modal-reset-btn" class="favset-modal-btn favset-modal-btn-secondary">重置</button>
<button type="button" id="favset-modal-prev-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">上一步</button>
<button type="button" id="favset-modal-next-btn" class="favset-modal-btn favset-modal-btn-primary" disabled>下一步</button>
<button type="button" id="favset-modal-submit-btn" class="favset-modal-btn favset-modal-btn-primary" style="display:none;">送出</button>
<button type="button" id="favset-modal-close-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">關閉</button>
</footer>
</div>
</div>
<script>
(() => {
// 類別資料 (新增更多類別)
const categories = [
{id: 1, name: "電子產品"},
{id: 2, name: "書籍"},
{id: 3, name: "服飾"},
{id: 4, name: "居家用品"},
{id: 5, name: "玩具"},
{id: 6, name: "運動"},
{id: 7, name: "美妝"},
{id: 8, name: "食品"},
{id: 9, name: "音樂用品"},
{id: 10, name: "辦公用品"},
];
// 產品資料(更多產品,方便隨機)
const products = [
// 電子產品
{id: 101, name: "無線耳機", categoryId: 1, tags: ["音訊","無線","藍牙"], image: "https://via.placeholder.com/150?text=%E7%84%A1%E7%B7%9A%E8%80%B3%E6%A9%9F"},
{id: 102, name: "智慧手機", categoryId: 1, tags: ["行動裝置","Android","iOS"], image: "https://via.placeholder.com/150?text=%E6%99%BA%E6%85%A7%E6%89%8B%E6%A9%9F"},
{id: 103, name: "筆記型電腦", categoryId: 1, tags: ["電腦","工作","辦公"], image: "https://via.placeholder.com/150?text=%E7%AD%86%E8%A8%98%E5%9E%8B%E9%9B%BB%E8%85%A6"},
{id: 104, name: "藍牙音箱", categoryId: 1, tags: ["音樂","無線","攜帶"], image: "https://via.placeholder.com/150?text=%E8%97%8D%E7%89%99%E9%9F%B3%E7%AE%B1"},
{id: 105, name: "電子閱讀器", categoryId: 1, tags: ["閱讀","電子書"], image: "https://via.placeholder.com/150?text=%E9%9B%BB%E5%AD%90%E9%96%B1%E8%AE%80%E5%99%A8"},
{id: 106, name: "智慧手錶", categoryId: 1, tags: ["穿戴裝置","健康","運動"], image: "https://via.placeholder.com/150?text=%E6%99%BA%E6%85%A7%E6%89%8B%E9%8C%B6"},
{id: 107, name: "USB隨身碟", categoryId: 1, tags: ["儲存","電腦配件"], image: "https://via.placeholder.com/150?text=USB%E9%9A%A8%E8%BA%AB%E7%A2%9F"},
// 書籍
{id: 201, name: "推理小說", categoryId: 2, tags: ["小說","推理","懸疑"], image: "https://via.placeholder.com/150?text=%E6%8E%A8%E7%90%86%E5%B0%8F%E8%AA%AA"},
{id: 202, name: "自我成長指南", categoryId: 2, tags: ["勵志","心靈"], image: "https://via.placeholder.com/150?text=%E8%87%AA%E6%88%91%E6%88%90%E9%95%B7"},
{id: 203, name: "旅遊地圖", categoryId: 2, tags: ["旅遊","指南"], image: "https://via.placeholder.com/150?text=%E6%97%85%E9%81%8A%E5%9C%B0%E5%9C%96"},
{id: 204, name: "烹飪書", categoryId: 2, tags: ["料理","食譜"], image: "https://via.placeholder.com/150?text=%E7%83%B9%E9%A3%AA%E6%9B%B8"},
{id: 205, name: "漫畫", categoryId: 2, tags: ["漫畫","娛樂"], image: "https://via.placeholder.com/150?text=%E6%BC%AB%E7%95%AB"},
// 服飾
{id: 301, name: "潮流T恤", categoryId: 3, tags: ["服裝","休閒"], image: "https://via.placeholder.com/150?text=T%E6%81%A4"},
{id: 302, name: "牛仔褲", categoryId: 3, tags: ["服裝","牛仔"], image: "https://via.placeholder.com/150?text=%E7%89%9B%E4%BB%94%E8%A4%B2"},
{id: 303, name: "運動鞋", categoryId: 3, tags: ["鞋子","運動"], image: "https://via.placeholder.com/150?text=%E9%81%8B%E5%8B%95%E9%9E%8B"},
{id: 304, name: "風衣外套", categoryId: 3, tags: ["服裝","外套"], image: "https://via.placeholder.com/150?text=%E9%A2%A8%E8%A1%A3"},
{id: 305, name: "帽子", categoryId: 3, tags: ["配件"], image: "https://via.placeholder.com/150?text=%E5%B8%BD%E5%AD%90"},
{id: 306, name: "圍巾", categoryId: 3, tags: ["保暖","配件"], image: "https://via.placeholder.com/150?text=%E5%9C%8D%E5%B7%BE"},
// 居家用品
{id: 401, name: "攪拌機", categoryId: 4, tags: ["廚房","電器"], image: "https://via.placeholder.com/150?text=%E6%94%AA%E6%8B%8C%E6%A9%9F"},
{id: 402, name: "咖啡機", categoryId: 4, tags: ["咖啡","電器"], image: "https://via.placeholder.com/150?text=%E5%92%96%E5%95%A1%E6%A9%9F"},
{id: 403, name: "吸塵器", categoryId: 4, tags: ["清潔","家電"], image: "https://via.placeholder.com/150?text=%E5%90%B8%E5%A1%B0%E5%99%A8"},
{id: 404, name: "空氣清淨機", categoryId: 4, tags: ["清潔","健康"], image: "https://via.placeholder.com/150?text=%E7%A9%BA%E6%B0%A3%E6%B8%85%E6%B7%86%E6%A9%9F"},
{id: 405, name: "電風扇", categoryId: 4, tags: ["家電","涼爽"], image: "https://via.placeholder.com/150?text=%E9%9B%BB%E9%A2%A8%E6%89%87"},
// 玩具
{id: 501, name: "積木", categoryId: 5, tags: ["玩具","益智"], image: "https://via.placeholder.com/150?text=%E7%A9%8D%E6%9C%A8"},
{id: 502, name: "公仔", categoryId: 5, tags: ["玩具","收藏"], image: "https://via.placeholder.com/150?text=%E5%85%AC%E4%BB%94"},
{id: 503, name: "遙控車", categoryId: 5, tags: ["玩具","遙控"], image: "https://via.placeholder.com/150?text=%E9%81%A0%E6%8E%A7%E8%BB%8A"},
{id: 504, name: "拼圖", categoryId: 5, tags: ["玩具","益智"], image: "https://via.placeholder.com/150?text=%E6%8B%BC%E5%9C%96"},
{id: 505, name: "跳跳馬", categoryId: 5, tags: ["玩具","運動"], image: "https://via.placeholder.com/150?text=%E8%B7%B3%E8%B7%B3%E9%A6%AC"},
// 運動
{id: 601, name: "瑜珈墊", categoryId: 6, tags: ["運動","瑜珈"], image: "https://via.placeholder.com/150?text=%E7%91%9C%E7%8F%88%E5%A2%8A"},
{id: 602, name: "籃球", categoryId: 6, tags: ["運動","球類"], image: "https://via.placeholder.com/150?text=%E7%B1%83%E7%90%83"},
{id: 603, name: "跑步鞋", categoryId: 6, tags: ["鞋子","跑步"], image: "https://via.placeholder.com/150?text=%E8%B7%91%E6%AD%A5%E9%9E%8B"},
{id: 604, name: "足球", categoryId: 6, tags: ["運動","球類"], image: "https://via.placeholder.com/150?text=%E8%B6%B3%E7%90%83"},
// 美妝
{id: 701, name: "口紅", categoryId: 7, tags: ["美妝","彩妝"], image: "https://via.placeholder.com/150?text=%E5%8F%A3%E7%B4%85"},
{id: 702, name: "面霜", categoryId: 7, tags: ["美妝","保養"], image: "https://via.placeholder.com/150?text=%E9%9D%A2%E9%9C%9C"},
{id: 703, name: "香水", categoryId: 7, tags: ["美妝","香氛"], image: "https://via.placeholder.com/150?text=%E9%A6%99%E6%B0%B4"},
// 食品
{id: 801, name: "巧克力", categoryId: 8, tags: ["甜點","零食"], image: "https://via.placeholder.com/150?text=%E5%B7%A7%E5%85%8B%E5%8A%9B"},
{id: 802, name: "咖啡豆", categoryId: 8, tags: ["飲品","咖啡"], image: "https://via.placeholder.com/150?text=%E5%92%96%E5%95%A1%E8%B1%86"},
{id: 803, name: "蘋果", categoryId: 8, tags: ["水果","健康"], image: "https://via.placeholder.com/150?text=%E8%98%8B%E6%9E%9C"},
// 音樂用品
{id: 901, name: "電吉他", categoryId: 9, tags: ["樂器","吉他"], image: "https://via.placeholder.com/150?text=%E9%9B%BB%E5%90%89%E4%BB%96"},
{id: 902, name: "鋼琴", categoryId: 9, tags: ["樂器","鍵盤"], image: "https://via.placeholder.com/150?text=%E9%8B%BC%E7%90%B4"},
// 辦公用品
{id: 1001, name: "筆記本", categoryId: 10, tags: ["辦公","文具"], image: "https://via.placeholder.com/150?text=%E7%AD%86%E8%A8%98%E6%9C%AC"},
{id: 1002, name: "鋼筆", categoryId: 10, tags: ["文具"], image: "https://via.placeholder.com/150?text=%E9%8B%BC%E7%AD%86"},
{id: 1003, name: "印表機", categoryId: 10, tags: ["辦公","設備"], image: "https://via.placeholder.com/150?text=%E5%8D%B0%E8%A1%A8%E6%A9%9F"},
];
// DOM Elements
const modalBackdrop = document.getElementById("favset-modal-backdrop");
const modalBody = modalBackdrop.querySelector(".favset-modal-body");
const btnReset = document.getElementById("favset-modal-reset-btn");
const btnPrev = document.getElementById("favset-modal-prev-btn");
const btnNext = document.getElementById("favset-modal-next-btn");
const btnSubmit = document.getElementById("favset-modal-submit-btn");
const btnClose = document.getElementById("favset-modal-close-btn");
const btnOpen = document.getElementById("favset-modal-open-btn");
// State
let currentStep = 1;
const totalSteps = 4;
let selectedCategoryIds = [];
let randomProductsForSelection = [];
let selectedProductIds = [];
let firstSubmitDone = false;
// N 指定選擇數量
const N = 3;
// Helpers
function clearModalBody() {
modalBody.innerHTML = "";
}
function createElem(type, classNames, textContent) {
const el = document.createElement(type);
if (classNames) el.className = classNames;
if (textContent !== undefined && textContent !== null) el.textContent = textContent;
return el;
}
// Step 1 - 選擇類別 (改用卡片,像商品一樣)
function renderStep1() {
clearModalBody();
const title = createElem("div", "favset-modal-step-title", `步驟 1:選擇 ${N} 個您喜歡的類別`);
modalBody.appendChild(title);
const info = createElem("div", "favset-modal-info-text", `請點擊下方卡片選擇您的喜好類別(需選擇 ${N} 個)`);
modalBody.appendChild(info);
const list = createElem("div", "favset-modal-category-list");
categories.forEach(cat => {
const card = createElem("div", "favset-modal-category-item");
card.setAttribute("tabindex", "0");
card.setAttribute("role", "checkbox");
card.setAttribute("aria-checked", selectedCategoryIds.includes(cat.id) ? "true" : "false");
card.textContent = cat.name;
if (selectedCategoryIds.includes(cat.id)) card.classList.add("favset-modal-selected");
card.addEventListener("click", () => {
const id = cat.id;
if (selectedCategoryIds.includes(id)) {
selectedCategoryIds = selectedCategoryIds.filter(v => v !== id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked", "false");
} else {
if (selectedCategoryIds.length < N) {
selectedCategoryIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked", "true");
}
}
updateNextButton();
});
card.addEventListener("keydown", e => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
}
// 更新下一步按鈕狀態 (Step1 & 3)
function updateNextButton() {
if (currentStep === 1) {
btnNext.disabled = selectedCategoryIds.length !== N;
} else if (currentStep === 3) {
btnNext.disabled = selectedProductIds.length !== N;
} else {
btnNext.disabled = false;
}
}
// Step 2 - 隨機選產品,每次隨機 N*2 件以上 (方便選)
function randomizeProductsForSelection() {
randomProductsForSelection = [];
selectedProductIds = [];
const filtered = products.filter(p => selectedCategoryIds.includes(p.categoryId));
if (filtered.length === 0) return;
// 洗牌
const shuffled = filtered.sort(() => 0.5 - Math.random());
// 取N*2,如超過總數取全部
const count = Math.min(shuffled.length, N * 2);
randomProductsForSelection = shuffled.slice(0, count);
}
// Step 3 - 選擇產品
function renderStep3() {
clearModalBody();
const title = createElem("div", "favset-modal-step-title", `步驟 3:從隨機產品中選擇 ${N} 件喜愛的商品`);
modalBody.appendChild(title);
const info = createElem("div", "favset-modal-info-text", `請點擊產品卡片選擇您的喜愛商品(需選擇 ${N} 件)`);
modalBody.appendChild(info);
if (randomProductsForSelection.length === 0) {
const noData = createElem("div", "", "選擇的類別沒有符合的產品。");
modalBody.appendChild(noData);
btnNext.disabled = true;
return;
}
const list = createElem("div", "favset-modal-product-list");
randomProductsForSelection.forEach(prod => {
const card = createElem("div", "favset-modal-product-item");
card.setAttribute("tabindex", "0");
card.setAttribute("role", "checkbox");
card.setAttribute("aria-checked", selectedProductIds.includes(prod.id) ? "true" : "false");
// Image
const img = createElem("img", "favset-modal-product-image");
img.src = prod.image;
img.alt = prod.name;
card.appendChild(img);
// Info container
const infoDiv = createElem("div", "favset-modal-product-info");
// 名稱
const nameEl = createElem("p", "favset-modal-product-name", prod.name);
// 類別名稱
const cname = categories.find(c => c.id === prod.categoryId)?.name || "未知類別";
const catEl = createElem("p", "favset-modal-product-category", cname);
// 標籤
const tagsEl = createElem("p", "favset-modal-product-tags", prod.tags.map(t => `#${t}`).join(" "));
infoDiv.appendChild(nameEl);
infoDiv.appendChild(catEl);
infoDiv.appendChild(tagsEl);
card.appendChild(infoDiv);
// 點擊切換選擇狀態
card.addEventListener("click", () => {
const id = prod.id;
if (selectedProductIds.includes(id)) {
selectedProductIds = selectedProductIds.filter(v => v !== id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked", "false");
} else {
if (selectedProductIds.length < N) {
selectedProductIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked", "true");
}
}
updateNextButton();
});
// 鍵盤無障礙選擇
card.addEventListener("keydown", e => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
updateNextButton();
}
// Step 4 - 預覽
function renderStep4() {
clearModalBody();
const title = createElem("div", "favset-modal-step-title", "步驟 4:預覽您的選擇");
modalBody.appendChild(title);
const previewBlock = createElem("div", "favset-modal-preview-block");
// 類別區塊
const catSection = createElem("section", "favset-modal-preview-section");
const catTitle = createElem("div", "favset-modal-preview-title", "已選擇的類別");
catSection.appendChild(catTitle);
selectedCategoryIds.forEach(cid => {
const cat = categories.find(c => c.id === cid);
if (cat) {
const cItem = createElem("div", "favset-modal-preview-category-item", cat.name);
catSection.appendChild(cItem);
}
});
previewBlock.appendChild(catSection);
// 產品區塊
const prodSection = createElem("section", "favset-modal-preview-section");
const prodTitle = createElem("div", "favset-modal-preview-title", "已選擇的商品");
prodSection.appendChild(prodTitle);
const prodList = createElem("div", "favset-modal-preview-product-list");
selectedProductIds.forEach(pid => {
const prod = products.find(p => p.id === pid);
if (prod) {
const item = createElem("div", "favset-modal-preview-product-item");
const img = createElem("img", "favset-modal-preview-product-image");
img.src = prod.image;
img.alt = prod.name;
item.appendChild(img);
const info = createElem("div", "favset-modal-preview-product-info");
const nameEl = createElem("p", "favset-modal-preview-product-name", prod.name);
const cname = categories.find(c => c.id === prod.categoryId)?.name || "未知類別";
const catEl = createElem("p", "favset-modal-preview-product-category", cname);
const tagsEl = createElem("p", "favset-modal-preview-product-tags", prod.tags.map(t => `#${t}`).join(" "));
info.appendChild(nameEl);
info.appendChild(catEl);
info.appendChild(tagsEl);
item.appendChild(info);
prodList.appendChild(item);
}
});
prodSection.appendChild(prodList);
previewBlock.appendChild(prodSection);
modalBody.appendChild(previewBlock);
}
// 更新 footer 按鈕狀態
function updateFooterButtons() {
btnReset.style.display = "inline-block";
btnPrev.style.display = currentStep > 1 ? "inline-block" : "none";
btnNext.style.display = currentStep < totalSteps ? "inline-block" : "none";
btnSubmit.style.display = currentStep === totalSteps ? "inline-block" : "none";
btnClose.style.display = firstSubmitDone ? "inline-block" : "none";
updateNextButton();
}
// 切換步驟
function goToStep(step) {
currentStep = step;
if (currentStep === 1) {
renderStep1();
} else if (currentStep === 2) {
randomizeProductsForSelection();
currentStep = 3; // 直接跳 step 3 介面
renderStep3();
} else if (currentStep === 3) {
renderStep3();
} else if (currentStep === 4) {
renderStep4();
}
updateFooterButtons();
}
// 重置所有選擇
function resetAll() {
if (!confirm("確認要重置所有選擇嗎?")) return;
selectedCategoryIds = [];
selectedProductIds = [];
randomProductsForSelection = [];
currentStep = 1;
firstSubmitDone = false;
btnClose.style.display = "none";
goToStep(1);
}
// 送出
function submitSelections() {
if (selectedCategoryIds.length !== N) {
alert(`請選擇 ${N} 個類別`);
return;
}
if (selectedProductIds.length !== N) {
alert(`請選擇 ${N} 件商品`);
return;
}
console.log("送出的類別ID:", selectedCategoryIds);
console.log("送出的商品ID:", selectedProductIds);
alert("您的喜好已成功送出!");
firstSubmitDone = true;
btnClose.style.display = "inline-block";
goToStep(4);
}
// 開啟 Modal
function openModal() {
modalBackdrop.classList.add("favset-modal-show");
document.body.classList.add("favset-modal-noscroll");
if (!firstSubmitDone) {
btnClose.style.display = "none";
}
goToStep(1);
}
// 關閉 Modal
function closeModal() {
modalBackdrop.classList.remove("favset-modal-show");
document.body.classList.remove("favset-modal-noscroll");
}
// 事件綁定
btnOpen.addEventListener("click", openModal);
btnReset.addEventListener("click", resetAll);
btnPrev.addEventListener("click", () => {
if (currentStep === 3) {
goToStep(1);
} else if (currentStep === 4) {
goToStep(3);
}
});
btnNext.addEventListener("click", () => {
if (currentStep === 1) {
goToStep(2);
} else if (currentStep === 3) {
goToStep(4);
}
});
btnSubmit.addEventListener("click", submitSelections);
btnClose.addEventListener("click", () => {
if (firstSubmitDone) {
closeModal();
} else {
alert("請先完成送出才能關閉視窗。");
}
});
// 點擊遮罩視窗 (要求首次送出前不能關閉)
modalBackdrop.addEventListener("click", e => {
if (e.target === modalBackdrop) {
if (firstSubmitDone) {
closeModal();
} else {
alert("請先完成送出您的喜好後才能關閉視窗。");
}
}
});
// Esc 鍵關閉限制
document.addEventListener("keydown", e => {
if (modalBackdrop.classList.contains("favset-modal-show")) {
if (e.key === "Escape") {
if (firstSubmitDone) {
closeModal();
} else {
alert("請先完成送出您的喜好後才能關閉視窗。");
}
}
}
});
})();
</script>
</body>
</html>
使用說明:
開啟彈跳視窗後,Step 1 選擇 3 個喜歡的類別(點擊卡片選擇,點再次取消)
下一步後隨機顯示該類別的 多於 3 個 產品供挑選(卡片點擊切換選擇)
Step 4 預覽詳細的類別與產品(含圖片與標籤)
第一次送出必須完成,且未送出前無法關閉彈窗
送出後可關閉與重啟設定視窗
這樣 Step 1、Step 3 的選擇邏輯與交互完全統一,體驗會更自然舒服並且功能健全。
3. 修改 Step 1 與 Step 2 呼叫 js Copy code
async function openModal() {
modalBackdrop.classList.add("favset-modal-show");
document.body.classList.add("favset-modal-noscroll");
if(!firstSubmitDone) {
btnClose.style.display = "none";
}
// 第一次打開先抓類別
await fetchCategories();
goToStep(1);
}
Step 2 階段先以 Fetch 下載產品資料代替原本隨機生成產品:
js Copy code
async function goToStep(step) {
currentStep = step;
if(currentStep === 1) {
renderStep1();
} else if(currentStep === 2) {
// 先利用 fetchProductsForSelectedCategories 拿到 products
await fetchProductsForSelectedCategories(selectedCategoryIds);
// 執行隨機邏輯從 products 撈 N*2 件
randomizeProductsForSelection();
currentStep = 3;
renderStep3();
} else if(currentStep === 3) {
renderStep3();
} else if(currentStep === 4) {
renderStep4();
}
updateFooterButtons();
}
4. 其他幾點說明:
您的 Controller 端回傳的 JSON 應該符合前端使用的資料結構:
categories 要有 id 與 name
products 要有 id, name, categoryId, tags[], image(若沒有 image URL,您需要自行調整補充)
若您的產品API中的 categoryId 屬性名稱不符,例如是 category_id,您要在 JS 取用時替換名稱,以配合。
如果需要在前端多做欄位調整(例如製作tags陣列,或image補圖),也可以在收到資料時做轉換
5. 完整簡化的重點版修改示範片段(以貼入前述範例為基準): js Copy code
// 省略舊的 dummy categories、products
// 先定義空陣列存資料
let categories = [];
let products = [];
// 從後端取得類別
async function fetchCategories(search = '') {
try {
const url = new URL('<?php echo base_url("category/get_product_parent_categories") ?>', window.location.origin);
if(search) url.searchParams.append('search', search);
const res = await fetch(url.toString());
if(!res.ok) throw new Error("取得類別失敗");
categories = await res.json();
} catch(e) {
alert(e.message);
categories = [];
}
}
// 取得多個類別產品並合併
async function fetchProductsForSelectedCategories(categoryIds = []) {
try {
const promises = categoryIds.map(cid => {
const url = new URL('<?php echo base_url("category/get_product_for_category") ?>', window.location.origin);
url.searchParams.append('category_id', cid);
return fetch(url.toString()).then(r=>{
if(!r.ok) throw new Error("取得產品失敗");
return r.json();
});
});
const results = await Promise.all(promises);
products = results.flat();
} catch(e) {
alert(e.message);
products = [];
}
}
// 呼叫 openModal() 時先 fetch categories
async function openModal() {
modalBackdrop.classList.add("favset-modal-show");
document.body.classList.add("favset-modal-noscroll");
if(!firstSubmitDone) btnClose.style.display="none";
await fetchCategories();
goToStep(1);
}
// Step 2 fetch products for selected categoryIds before rendering
async function goToStep(step) {
currentStep=step;
if(step === 1) {
renderStep1();
} else if(step === 2) {
await fetchProductsForSelectedCategories(selectedCategoryIds);
randomizeProductsForSelection();
currentStep=3;
renderStep3();
} else if(step ===3) {
renderStep3();
} else if(step ===4) {
renderStep4();
}
updateFooterButtons();
}
6. 附註
請將以上JS程式碼取代原本前端中 categories 與 products 的宣告及取代您彈跳視窗中相應位置
API URL 可用 PHP base_url() 等語法動態寫入,但測試環境可直接寫完整URL
再依您API回傳資料格式作必要欄位轉換:例如產品資料 categoryId 有時叫 category_id,以及圖片 URL 欄位名稱
有需要,我可以協助提供完整整合後的 JS 片段或完整修改版本,請告訴我。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>喜好設定彈跳視窗 - 伺服器整合版</title>
<style>
/* 同前面設計略過,直接複製貼上... */
/* Reset & base */
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
margin: 0;
background: #f5f7fa;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #222;
}
button {
font-family: inherit;
}
/* Modal backdrop */
.favset-modal-backdrop {
position: fixed;
inset: 0;
background: rgba(18, 25, 40, 0.6);
display: none;
justify-content: center;
align-items: center;
z-index: 11000;
padding: 12px 20px;
}
.favset-modal-backdrop.favset-modal-show {
display: flex;
}
/* Modal container */
.favset-modal-container {
background: #fff;
width: 100%;
max-width: 720px;
max-height: 90vh;
border-radius: 12px;
display: flex;
flex-direction: column;
box-shadow:
0 4px 8px rgba(0, 0, 0, 0.1),
0 12px 24px rgba(0, 0, 0, 0.15);
overflow: hidden;
}
/* Header */
.favset-modal-header {
background: #004aad;
color: #fff;
padding: 18px 28px;
font-weight: 700;
font-size: 1.375rem;
user-select: none;
}
/* Body */
.favset-modal-body {
padding: 20px 28px;
overflow-y: auto;
flex-grow: 1;
}
.favset-modal-body::-webkit-scrollbar {
width: 6px;
}
.favset-modal-body::-webkit-scrollbar-track {
background: transparent;
}
.favset-modal-body::-webkit-scrollbar-thumb {
background-color: #004aad;
border-radius: 3px;
}
/* Footer */
.favset-modal-footer {
background: #f9fbfd;
padding: 16px 28px;
display: flex;
justify-content: flex-end;
gap: 12px;
}
/* Buttons */
.favset-modal-btn {
font-weight: 600;
font-size: 1rem;
padding: 12px 22px;
border-radius: 6px;
cursor: pointer;
border: none;
user-select: none;
transition: background-color 0.25s ease, box-shadow 0.25s ease;
}
.favset-modal-btn-primary {
background-color: #004aad;
color: white;
box-shadow: 0 4px 10px rgb(0 74 173 / 0.2);
}
.favset-modal-btn-primary:hover:not(:disabled) {
background-color: #003177;
box-shadow: 0 6px 16px rgb(0 49 119 / 0.3);
}
.favset-modal-btn-secondary {
background-color: #e7ecf8;
color: #004aad;
}
.favset-modal-btn-secondary:hover {
background-color: #c5d1f1;
}
.favset-modal-btn:disabled {
background-color: #bcc6d4;
cursor: not-allowed;
box-shadow: none;
}
/* Step title */
.favset-modal-step-title {
font-size: 1.2rem;
font-weight: 700;
margin-bottom: 18px;
color: #0d1e40;
}
.favset-modal-info-text {
font-size: 1rem;
color: #2d3b64;
margin-bottom: 20px;
}
/* Step 1: categories cards */
.favset-modal-category-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 16px;
}
.favset-modal-category-item {
background: #fff;
border: 2px solid transparent;
border-radius: 14px;
box-shadow: 0 1px 4px rgb(0 0 0 / 0.06);
cursor: pointer;
display: flex;
flex-direction: column;
align-items: center;
font-weight: 600;
font-size: 1.1rem;
padding: 16px 12px;
color: #395584;
transition:
border-color 0.3s ease,
box-shadow 0.3s ease,
background-color 0.3s ease;
user-select: none;
outline-offset: 2px;
text-align: center;
}
.favset-modal-category-item:hover:not(.favset-modal-selected) {
border-color: #2561cc;
box-shadow: 0 3px 10px rgb(37 97 204 / 0.15);
}
.favset-modal-category-item.favset-modal-selected {
background-color: #eaf3ff;
border-color: #004aad;
box-shadow: 0 5px 20px rgb(0 74 173 / 0.3);
color: #004aad;
}
.favset-modal-category-image {
width: 64px;
height: 64px;
object-fit: contain;
margin-bottom: 8px;
border-radius: 8px;
background: #f0f3fa;
box-shadow: inset 0 0 6px #d0d8ef;
}
/* Step 3: products cards */
.favset-modal-product-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(150px,1fr));
gap: 16px;
}
.favset-modal-product-item {
background: #fff;
border: 2px solid transparent;
border-radius: 14px;
box-shadow:
0 1px 4px rgb(0 0 0 / 0.06);
cursor: pointer;
display: flex;
flex-direction: column;
user-select: none;
transition:
border-color 0.3s ease,
box-shadow 0.3s ease;
overflow: hidden;
}
.favset-modal-product-item:hover:not(.favset-modal-selected) {
border-color: #2561cc;
box-shadow: 0 3px 10px rgb(37 97 204 / 0.15);
}
.favset-modal-product-item.favset-modal-selected {
border-color: #004aad;
background-color: #eaf3ff;
box-shadow: 0 5px 20px rgb(0 74 173 / 0.3);
}
.favset-modal-product-image {
width: 100%;
aspect-ratio: 1 / 1;
object-fit: contain;
background: #f0f3fa;
border-bottom: 1px solid #e0e6f1;
}
.favset-modal-product-info {
padding: 12px 14px;
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 6px;
}
.favset-modal-product-name {
font-weight: 700;
font-size: 1rem;
color: #113366;
margin: 0;
line-height: 1.2;
}
.favset-modal-product-category {
font-size: 0.85rem;
color: #556a9b;
font-style: italic;
}
.favset-modal-product-tags {
font-size: 0.75rem;
color: #7789ac;
margin-top: auto;
}
/* Step 4: preview */
.favset-modal-preview-block {
display: flex;
flex-direction: column;
gap: 22px;
}
.favset-modal-preview-section {
background: #f7faff;
border-radius: 12px;
padding: 20px 24px;
box-shadow: inset 0 0 12px #dce9fc;
}
.favset-modal-preview-title {
font-weight: 700;
font-size: 1.15rem;
margin-bottom: 16px;
color: #2d3b64;
}
.favset-modal-preview-category-item {
display: inline-block;
background: #dde8ff;
color: #2e57c2;
font-weight: 600;
border-radius: 24px;
font-size: 0.95rem;
padding: 6px 16px;
margin: 4px 6px 4px 0;
user-select: none;
box-shadow: 0 2px 6px rgb(46 87 194 / 0.25);
}
.favset-modal-preview-product-list {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(220px,1fr));
gap: 16px;
}
.favset-modal-preview-product-item {
display: flex;
gap: 14px;
background: #fff;
border-radius: 12px;
box-shadow:
0 1px 8px rgba(0,0,0,0.06);
padding: 12px;
align-items: center;
}
.favset-modal-preview-product-image {
flex-shrink: 0;
width: 88px;
height: 88px;
object-fit: contain;
background: #f0f3fa;
border-radius: 10px;
border: 1.5px solid #cbd7fc;
}
.favset-modal-preview-product-info {
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 4px;
}
.favset-modal-preview-product-name {
font-weight: 700;
font-size: 1.05rem;
margin: 0;
color: #113366;
}
.favset-modal-preview-product-category {
font-size: 0.9rem;
font-style: italic;
color: #536498;
}
.favset-modal-preview-product-tags {
font-size: 0.8rem;
color: #7a89a9;
}
/* Responsive */
@media (max-width: 576px) {
.favset-modal-container {
max-width: 100%;
border-radius: 0;
max-height: 100vh;
}
.favset-modal-body {
padding: 16px 20px;
}
.favset-modal-footer {
padding: 12px 20px;
gap: 10px;
}
}
@media (max-width: 400px) {
.favset-modal-footer {
flex-wrap: wrap;
gap: 8px;
}
.favset-modal-btn {
flex: 1 1 100%;
padding: 14px;
font-size: 1.1rem;
}
}
</style>
</head>
<body>
<button id="favset-modal-open-btn" class="favset-modal-btn favset-modal-btn-primary" style="margin:24px auto 60px; display: block; max-width: 280px; width: 90%;">
開啟偏好設定
</button>
<div id="favset-modal-backdrop" class="favset-modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="favset-modal-header-title">
<div class="favset-modal-container" role="document" aria-describedby="favset-modal-desc" tabindex="0">
<header class="favset-modal-header">
<h2 id="favset-modal-header-title">設定您的喜好</h2>
</header>
<main class="favset-modal-body" id="favset-modal-desc" tabindex="0">
<!-- 內容動態渲染 -->
</main>
<footer class="favset-modal-footer">
<button type="button" id="favset-modal-reset-btn" class="favset-modal-btn favset-modal-btn-secondary">重置</button>
<button type="button" id="favset-modal-prev-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">上一步</button>
<button type="button" id="favset-modal-next-btn" class="favset-modal-btn favset-modal-btn-primary" disabled>下一步</button>
<button type="button" id="favset-modal-submit-btn" class="favset-modal-btn favset-modal-btn-primary" style="display:none;">送出</button>
<button type="button" id="favset-modal-close-btn" class="favset-modal-btn favset-modal-btn-secondary" style="display:none;">關閉</button>
</footer>
</div>
</div>
<script>
(() => {
// 請根據實際情況調整API的Base URL:
const API_BASE = window.location.origin + '/category/';
// state
let categories = [];
let products = [];
let selectedCategoryIds = [];
let randomProductsForSelection = [];
let selectedProductIds = [];
let currentStep = 1;
const totalSteps = 4;
const N = 3;
let firstSubmitDone = false;
// DOM Elements
const modalBackdrop = document.getElementById("favset-modal-backdrop");
const modalBody = modalBackdrop.querySelector(".favset-modal-body");
const btnReset = document.getElementById("favset-modal-reset-btn");
const btnPrev = document.getElementById("favset-modal-prev-btn");
const btnNext = document.getElementById("favset-modal-next-btn");
const btnSubmit = document.getElementById("favset-modal-submit-btn");
const btnClose = document.getElementById("favset-modal-close-btn");
const btnOpen = document.getElementById("favset-modal-open-btn");
// Util: 補image連結成完整url,缺圖片用預設圖
function buildImageUrl(path) {
if(!path) return 'https://via.placeholder.com/150?text=No+Image';
if(path.startsWith('http')) return path;
// 假設uploads為根目錄底下
return window.location.origin + '/' + path.replace(/^\/+/, '');
}
// Util: 將tags 字串 split成 陣列 (空字串回傳空陣列)
function parseTags(tagsStr) {
if(!tagsStr) return [];
return tagsStr.split(',').map(t=>t.trim()).filter(t=>t.length>0);
}
// --------------------------------------------------------
// 取得類別 (Step 1)
async function fetchCategories(search='') {
try {
const url = new URL(API_BASE + 'get_product_parent_categories');
if(search) url.searchParams.append('search', search);
const res = await fetch(url.toString());
if(!res.ok) throw new Error('無法取得類別資料');
const data = await res.json();
categories = data.map(c => ({
id: c.id,
name: c.name,
image: buildImageUrl(c.image),
}));
} catch(e) {
alert(e.message);
categories = [];
}
}
// 依類別ids 批次取得產品 (Step 2)
async function fetchProductsForSelectedCategories(categoryIds) {
try {
const promises = categoryIds.map(cid => {
const url = new URL(API_BASE + 'get_product_for_category');
url.searchParams.append('category_id', cid);
return fetch(url.toString()).then(res=>{
if(!res.ok) throw new Error(`取得分類${cid}產品失敗`);
return res.json();
});
});
const results = await Promise.all(promises);
const merged = results.flat();
products = merged.map(p => ({
id: p.id,
categoryId: p.category_id,
name: p.name,
image: buildImageUrl(p.image),
tags: parseTags(p.tags),
}));
} catch(e) {
alert(e.message);
products = [];
}
}
// ------------------------------------------
// Step 1 render - 選擇類別
function renderStep1() {
clearModalBody();
const title = createElem("div","favset-modal-step-title", `步驟 1:選擇 ${N} 個您喜歡的類別`);
modalBody.appendChild(title);
const info = createElem("div","favset-modal-info-text", `請點擊下方卡片選擇您的喜好類別(需選擇 ${N} 個)`);
modalBody.appendChild(info);
const list = createElem("div","favset-modal-category-list");
categories.forEach(cat => {
const card = createElem("div","favset-modal-category-item");
card.textContent = cat.name;
card.setAttribute("tabindex", "0");
card.setAttribute("role", "checkbox");
card.setAttribute("aria-checked", selectedCategoryIds.includes(cat.id) ? "true" : "false");
// 類別有圖片,放左上角
const img = createElem("img","favset-modal-category-image");
img.src = cat.image;
img.alt = cat.name;
card.prepend(img);
if(selectedCategoryIds.includes(cat.id)) {
card.classList.add("favset-modal-selected");
}
card.addEventListener("click", () => {
const id = cat.id;
if(selectedCategoryIds.includes(id)) {
selectedCategoryIds = selectedCategoryIds.filter(v=>v!==id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked", "false");
} else {
if(selectedCategoryIds.length < N) {
selectedCategoryIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked", "true");
}
}
updateNextButton();
});
card.addEventListener("keydown", e => {
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
}
// Step 3 render - 選擇商品
function renderStep3() {
clearModalBody();
const title = createElem("div","favset-modal-step-title", `步驟 3:從隨機產品中選擇 ${N} 件喜愛的商品`);
modalBody.appendChild(title);
const info = createElem("div","favset-modal-info-text", `請點擊產品卡片選擇您的喜愛商品(需選擇 ${N} 件)`);
modalBody.appendChild(info);
if(randomProductsForSelection.length === 0) {
const noData = createElem("div", "", "選擇的類別沒有符合的產品。");
modalBody.appendChild(noData);
btnNext.disabled = true;
return;
}
const list = createElem("div","favset-modal-product-list");
randomProductsForSelection.forEach(prod => {
const card = createElem("div","favset-modal-product-item");
card.setAttribute("tabindex","0");
card.setAttribute("role","checkbox");
card.setAttribute("aria-checked",selectedProductIds.includes(prod.id) ? "true" : "false");
const img = createElem("img","favset-modal-product-image");
img.src = prod.image;
img.alt = prod.name;
card.appendChild(img);
const infoDiv = createElem("div","favset-modal-product-info");
const nameEl = createElem("p","favset-modal-product-name", prod.name);
const cat = categories.find(c=>c.id === prod.categoryId);
const catName = cat ? cat.name : "未知類別";
const catEl = createElem("p","favset-modal-product-category", catName);
const tagsEl = createElem("p","favset-modal-product-tags", prod.tags.length ? prod.tags.map(t=>`#${t}`).join(" ") : "");
infoDiv.appendChild(nameEl);
infoDiv.appendChild(catEl);
if(prod.tags.length > 0){
infoDiv.appendChild(tagsEl);
}
card.appendChild(infoDiv);
card.addEventListener("click", ()=>{
const id = prod.id;
if(selectedProductIds.includes(id)) {
selectedProductIds = selectedProductIds.filter(v=>v!==id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked","false");
} else {
if(selectedProductIds.length < N) {
selectedProductIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked","true");
}
}
updateNextButton();
});
card.addEventListener("keydown", e=>{
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
updateNextButton();
}
// Step 4 preview
function renderStep4() {
clearModalBody();
const title = createElem("div","favset-modal-step-title", "步驟 4:預覽您的選擇");
modalBody.appendChild(title);
const previewBlock = createElem("div","favset-modal-preview-block");
// 類別
const catSection = createElem("section","favset-modal-preview-section");
const catTitle = createElem("div","favset-modal-preview-title", "已選擇的類別");
catSection.appendChild(catTitle);
selectedCategoryIds.forEach(cid=>{
const cat = categories.find(c=>c.id===cid);
if(cat) {
const cItem = createElem("div","favset-modal-preview-category-item", cat.name);
catSection.appendChild(cItem);
}
});
previewBlock.appendChild(catSection);
// 產品
const prodSection = createElem("section","favset-modal-preview-section");
const prodTitle = createElem("div","favset-modal-preview-title", "已選擇的商品");
prodSection.appendChild(prodTitle);
const prodList = createElem("div","favset-modal-preview-product-list");
selectedProductIds.forEach(pid=>{
const prod = products.find(p=>p.id===pid);
if(prod){
const item = createElem("div","favset-modal-preview-product-item");
const img = createElem("img","favset-modal-preview-product-image");
img.src = prod.image;
img.alt = prod.name;
item.appendChild(img);
const info = createElem("div","favset-modal-preview-product-info");
const nameEl = createElem("p","favset-modal-preview-product-name", prod.name);
const cat = categories.find(c=>c.id===prod.categoryId);
const catName = cat ? cat.name : "未知類別";
const catEl = createElem("p","favset-modal-preview-product-category", catName);
const tagsEl = createElem("p","favset-modal-preview-product-tags", prod.tags.length ? prod.tags.map(t=>`#${t}`).join(" ") : "");
info.appendChild(nameEl);
info.appendChild(catEl);
if(prod.tags.length>0){
info.appendChild(tagsEl);
}
item.appendChild(info);
prodList.appendChild(item);
}
});
prodSection.appendChild(prodList);
previewBlock.appendChild(prodSection);
modalBody.appendChild(previewBlock);
}
// btn next enable update
function updateNextButton() {
if(currentStep === 1) {
btnNext.disabled = selectedCategoryIds.length !== N;
} else if(currentStep === 3) {
btnNext.disabled = selectedProductIds.length !== N;
} else {
btnNext.disabled = false;
}
}
// 隨機選產品 N*2 個備選
function randomizeProductsForSelection() {
randomProductsForSelection = [];
selectedProductIds = [];
if(products.length === 0) return;
const shuffled = products.sort(()=>0.5 - Math.random());
const maxCount = Math.min(shuffled.length, N*2);
randomProductsForSelection = shuffled.slice(0, maxCount);
}
// 清空body
function clearModalBody() {
modalBody.innerHTML = '';
}
// 快速建元素
function createElem(type, classNames, textContent){
const el = document.createElement(type);
if(classNames) el.className = classNames;
if(textContent !== undefined && textContent !== null) el.textContent = textContent;
return el;
}
// 切換步驟
async function goToStep(step){
currentStep = step;
if(step === 1) {
renderStep1();
} else if(step === 2) {
// Step 2需先向後端載入產品
await fetchProductsForSelectedCategories(selectedCategoryIds);
randomizeProductsForSelection();
currentStep = 3;
renderStep3();
} else if(step === 3) {
renderStep3();
} else if(step === 4) {
renderStep4();
}
updateFooterButtons();
}
// 開啟modal
async function openModal(){
modalBackdrop.classList.add('favset-modal-show');
document.body.classList.add('favset-modal-noscroll');
if(!firstSubmitDone){
btnClose.style.display = 'none';
}
await fetchCategories();
goToStep(1);
}
// 關閉modal
function closeModal(){
modalBackdrop.classList.remove('favset-modal-show');
document.body.classList.remove('favset-modal-noscroll');
}
// 重置選擇
function resetAll(){
if(!confirm('確認要重置所有選擇嗎?')) return;
selectedCategoryIds = [];
selectedProductIds = [];
randomProductsForSelection = [];
firstSubmitDone = false;
btnClose.style.display = 'none';
goToStep(1);
}
// 送出表單
function submitSelections(){
if(selectedCategoryIds.length !== N){
alert(`請選擇 ${N} 個類別`);
return;
}
if(selectedProductIds.length !== N){
alert(`請選擇 ${N} 件商品`);
return;
}
// 送出資料給伺服器自行實作(這裡用console.log示範)
console.log('送出的類別 id:', selectedCategoryIds);
console.log('送出的商品 id:', selectedProductIds);
alert('喜好已成功送出!');
firstSubmitDone = true;
btnClose.style.display = 'inline-block';
goToStep(4);
}
// 更新footer按鈕
function updateFooterButtons(){
btnReset.style.display = 'inline-block';
btnPrev.style.display = currentStep > 1 ? 'inline-block' : 'none';
btnNext.style.display = currentStep < totalSteps ? 'inline-block' : 'none';
btnSubmit.style.display = currentStep === totalSteps ? 'inline-block' : 'none';
btnClose.style.display = firstSubmitDone ? 'inline-block' : 'none';
updateNextButton();
}
// 事件綁定
btnOpen.addEventListener('click', openModal);
btnReset.addEventListener('click', resetAll);
btnPrev.addEventListener('click', () => {
if(currentStep===3){
goToStep(1);
} else if(currentStep===4){
goToStep(3);
}
});
btnNext.addEventListener('click', () => {
if(currentStep===1){
goToStep(2);
} else if(currentStep===3){
goToStep(4);
}
});
btnSubmit.addEventListener('click', submitSelections);
btnClose.addEventListener('click', ()=>{
if(firstSubmitDone){
closeModal();
} else {
alert('請先完成送出才能關閉視窗。');
}
});
modalBackdrop.addEventListener('click', e=>{
if(e.target === modalBackdrop){
if(firstSubmitDone){
closeModal();
} else {
alert('請先完成送出您的喜好後才能關閉視窗。');
}
}
});
document.addEventListener('keydown', e=>{
if(modalBackdrop.classList.contains('favset-modal-show')){
if(e.key==='Escape'){
if(firstSubmitDone){
closeModal();
} else {
alert('請先完成送出您的喜好後才能關閉視窗。');
}
}
}
});
})();
</script>
</body>
</html>
使用說明:
開啟按鈕會先用 AJAX 抓取類別(含圖片),並渲染 Step 1
選擇完三個類別,下一步會針對這三類別各別呼叫API取得商品,合併後隨機抽出多筆顯示,供Step 3選擇三件
Step4呈現預覽列表(類別卡有圖片,商品卡顯示圖片、名稱、分類、標籤)
第一次送出前不能關閉彈窗,送出後方可關閉視窗
所有資料動態從API取得,不需前端固定Dummy Data
任何欄位結構改動,請適當調整映射邏輯 map(),因為您給的範例JSON並非完美符合前端預設格式。
此外,圖片若路徑為相對路徑,程式會自動補上主機根目錄,若您的路徑不一樣,請調整 buildImageUrl() 函式。
如需幫您串接送出資料或其他功能,歡迎再次詢問!祝開發順利!
And the related model function:
public function update_favorite_categories_products(data)
{
// 取得當前登入使用者ID (透過 ion_auth)
user_id = $this->ion_auth->user()->row()->id;
code Copy code
$catFav = json_encode($data['selectedCategoryIds'] ?? []);
$productFav = json_encode($data['selectedProductIds'] ?? []);
$cat_data = [
'user_id' => $user_id,
'category_ids' => $catFav,
'products_ids' => $productFav,
'date_updated' => date_format(date(),"Y-m-d H:i:s");
];
$preRecord = fetch_details("favset", ['user_id' => $user_id]);
if(count($preRecord) > 0){
$this->db->where('id', $user_id);
$this->db->update('favset', $cat_data);
} else {
$this->db->insert('favset', $cat_data);
}
}
Please integrate the above function and the auto open function (if user not submit yet and logged-in), also the function for open the modal anywhere.
Provide the full updated code of java script
(() => {
const API_BASE = window.location.origin + '/category/';
// 假設從後端輸出兩個全域變數 (可自行調整命名與取得方式)
// 你需要在PHP模板以JS腳本設定它們
// 例如:
// <script>window.is_logged_in = <?php echo json_encode($is_logged_in); ?>;</script>
// <script>window.cat_favorites = <?php echo json_encode($cat_favorites); ?>;</script>
// 如果你還沒輸出,請自行在頁面加入上面指令
// state
let categories = [];
let products = [];
let selectedCategoryIds = [];
let randomProductsForSelection = [];
let selectedProductIds = [];
let currentStep = 1;
const totalSteps = 4;
const N = 3;
let firstSubmitDone = false;
// DOM Elements
const modalBackdrop = document.getElementById("favset-modal-backdrop");
const modalBody = modalBackdrop.querySelector(".favset-modal-body");
const btnReset = document.getElementById("favset-modal-reset-btn");
const btnPrev = document.getElementById("favset-modal-prev-btn");
const btnNext = document.getElementById("favset-modal-next-btn");
const btnSubmit = document.getElementById("favset-modal-submit-btn");
const btnClose = document.getElementById("favset-modal-close-btn");
const btnOpen = document.getElementById("favset-modal-open-btn");
// ================= Utility Function ======================
function buildImageUrl(path) {
if(!path) return 'https://via.placeholder.com/150?text=No+Image';
if(path.startsWith('http')) return path;
return window.location.origin + '/' + path.replace(/^\/+/, '');
}
function parseTags(tagsStr) {
if(!tagsStr) return [];
return tagsStr.split(',').map(t=>t.trim()).filter(t=>t.length>0);
}
function clearModalBody() {
modalBody.innerHTML = '';
}
function createElem(type, classNames, textContent){
const el = document.createElement(type);
if(classNames) el.className = classNames;
if(textContent !== undefined && textContent !== null) el.textContent = textContent;
return el;
}
// ================== Fetch API ============================
async function fetchCategories(search='') {
try {
const url = new URL(API_BASE + 'get_product_parent_categories');
if(search) url.searchParams.append('search', search);
const res = await fetch(url.toString());
if(!res.ok) throw new Error('無法取得類別資料');
const data = await res.json();
categories = data.map(c => ({
id: c.id,
name: c.name,
image: buildImageUrl(c.image),
}));
} catch(e) {
alert(e.message);
categories = [];
}
}
async function fetchProductsForSelectedCategories(categoryIds) {
try {
const promises = categoryIds.map(cid => {
const url = new URL(API_BASE + 'get_product_for_category');
url.searchParams.append('category_id', cid);
return fetch(url.toString()).then(res=>{
if(!res.ok) throw new Error(`取得分類${cid}產品失敗`);
return res.json();
});
});
const results = await Promise.all(promises);
const merged = results.flat();
products = merged.map(p => ({
id: p.id,
categoryId: p.category_id,
name: p.name,
image: buildImageUrl(p.image),
tags: parseTags(p.tags),
}));
} catch(e) {
alert(e.message);
products = [];
}
}
// ================== Render Steps ==========================
function renderStep1() {
clearModalBody();
const title = createElem("div","favset-modal-step-title", `步驟 1:選擇 ${N} 個您喜歡的類別`);
modalBody.appendChild(title);
const info = createElem("div","favset-modal-info-text", `請點擊下方卡片選擇您的喜好類別(需選擇 ${N} 個)`);
modalBody.appendChild(info);
const list = createElem("div","favset-modal-category-list");
categories.forEach(cat => {
const card = createElem("div","favset-modal-category-item");
card.textContent = cat.name;
card.setAttribute("tabindex", "0");
card.setAttribute("role", "checkbox");
card.setAttribute("aria-checked", selectedCategoryIds.includes(cat.id) ? "true" : "false");
const img = createElem("img","favset-modal-category-image");
img.src = cat.image;
img.alt = cat.name;
card.prepend(img);
if(selectedCategoryIds.includes(cat.id)) {
card.classList.add("favset-modal-selected");
}
card.addEventListener("click", () => {
const id = cat.id;
if(selectedCategoryIds.includes(id)) {
selectedCategoryIds = selectedCategoryIds.filter(v=>v!==id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked", "false");
} else {
if(selectedCategoryIds.length < N) {
selectedCategoryIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked", "true");
}
}
updateNextButton();
});
card.addEventListener("keydown", e => {
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
}
function renderStep3() {
clearModalBody();
const title = createElem("div","favset-modal-step-title", `步驟 3:從隨機產品中選擇 ${N} 件喜愛的商品`);
modalBody.appendChild(title);
const info = createElem("div","favset-modal-info-text", `請點擊產品卡片選擇您的喜愛商品(需選擇 ${N} 件)`);
modalBody.appendChild(info);
if(randomProductsForSelection.length === 0) {
const noData = createElem("div", "", "選擇的類別沒有符合的產品。");
modalBody.appendChild(noData);
btnNext.disabled = true;
return;
}
const list = createElem("div","favset-modal-product-list");
randomProductsForSelection.forEach(prod => {
const card = createElem("div","favset-modal-product-item");
card.setAttribute("tabindex","0");
card.setAttribute("role","checkbox");
card.setAttribute("aria-checked",selectedProductIds.includes(prod.id) ? "true" : "false");
const img = createElem("img","favset-modal-product-image");
img.src = prod.image;
img.alt = prod.name;
card.appendChild(img);
const infoDiv = createElem("div","favset-modal-product-info");
const nameEl = createElem("p","favset-modal-product-name", prod.name);
const cat = categories.find(c=>c.id === prod.categoryId);
const catName = cat ? cat.name : "未知類別";
const catEl = createElem("p","favset-modal-product-category", catName);
const tagsEl = createElem("p","favset-modal-product-tags", prod.tags.length ? prod.tags.map(t=>`#${t}`).join(" ") : "");
infoDiv.appendChild(nameEl);
infoDiv.appendChild(catEl);
if(prod.tags.length > 0){
infoDiv.appendChild(tagsEl);
}
card.appendChild(infoDiv);
card.addEventListener("click", ()=>{
const id = prod.id;
if(selectedProductIds.includes(id)) {
selectedProductIds = selectedProductIds.filter(v => v !== id);
card.classList.remove("favset-modal-selected");
card.setAttribute("aria-checked", "false");
} else {
if(selectedProductIds.length < N) {
selectedProductIds.push(id);
card.classList.add("favset-modal-selected");
card.setAttribute("aria-checked", "true");
}
}
updateNextButton();
});
card.addEventListener("keydown", e=>{
if(e.key === " " || e.key === "Enter") {
e.preventDefault();
card.click();
}
});
list.appendChild(card);
});
modalBody.appendChild(list);
updateNextButton();
}
function renderStep4() {
clearModalBody();
const title = createElem("div","favset-modal-step-title", "步驟 4:預覽您的選擇");
modalBody.appendChild(title);
const previewBlock = createElem("div","favset-modal-preview-block");
const catSection = createElem("section","favset-modal-preview-section");
const catTitle = createElem("div","favset-modal-preview-title", "已選擇的類別");
catSection.appendChild(catTitle);
selectedCategoryIds.forEach(cid=>{
const cat = categories.find(c=>c.id===cid);
if(cat) {
const cItem = createElem("div","favset-modal-preview-category-item", cat.name);
catSection.appendChild(cItem);
}
});
previewBlock.appendChild(catSection);
const prodSection = createElem("section","favset-modal-preview-section");
const prodTitle = createElem("div","favset-modal-preview-title", "已選擇的商品");
prodSection.appendChild(prodTitle);
const prodList = createElem("div","favset-modal-preview-product-list");
selectedProductIds.forEach(pid=>{
const prod = products.find(p=>p.id===pid);
if(prod){
const item = createElem("div","favset-modal-preview-product-item");
const img = createElem("img","favset-modal-preview-product-image");
img.src = prod.image;
img.alt = prod.name;
item.appendChild(img);
const info = createElem("div","favset-modal-preview-product-info");
const nameEl = createElem("p","favset-modal-preview-product-name", prod.name);
const cat = categories.find(c=>c.id===prod.categoryId);
const catName = cat ? cat.name : "未知類別";
const catEl = createElem("p","favset-modal-preview-product-category", catName);
const tagsEl = createElem("p","favset-modal-preview-product-tags", prod.tags.length ? prod.tags.map(t=>`#${t}`).join(" ") : "");
info.appendChild(nameEl);
info.appendChild(catEl);
if(prod.tags.length>0){
info.appendChild(tagsEl);
}
item.appendChild(info);
prodList.appendChild(item);
}
});
prodSection.appendChild(prodList);
previewBlock.appendChild(prodSection);
modalBody.appendChild(previewBlock);
}
// 隨機 N*2 產品給 Step3 選
function randomizeProductsForSelection() {
randomProductsForSelection = [];
selectedProductIds = [];
if(products.length === 0) return;
const shuffled = products.slice().sort(()=>0.5 - Math.random());
const maxCount = Math.min(shuffled.length, N*2);
randomProductsForSelection = shuffled.slice(0, maxCount);
}
// update 下一步按鈕是否啟用
function updateNextButton() {
if(currentStep === 1) {
btnNext.disabled = selectedCategoryIds.length !== N;
} else if(currentStep === 3) {
btnNext.disabled = selectedProductIds.length !== N;
} else {
btnNext.disabled = false;
}
}
// 切換步驟,Step 2有異步取得產品
async function goToStep(step){
currentStep = step;
if(step === 1){
renderStep1();
} else if(step === 2){
await fetchProductsForSelectedCategories(selectedCategoryIds);
randomizeProductsForSelection();
currentStep = 3;
renderStep3();
} else if(step === 3){
renderStep3();
} else if(step === 4){
renderStep4();
}
updateFooterButtons();
}
// 開啟modal
async function openModal(){
modalBackdrop.classList.add('favset-modal-show');
document.body.classList.add('favset-modal-noscroll');
if(!firstSubmitDone){
btnClose.style.display = 'none';
}
await fetchCategories();
goToStep(1);
}
// 手動從外部呼叫此函數開啟
window.favsetModalOpen = openModal;
// 關閉modal
function closeModal(){
modalBackdrop.classList.remove('favset-modal-show');
document.body.classList.remove('favset-modal-noscroll');
}
// 重置所有選擇
function resetAll(){
if(!confirm('確認要重置所有選擇嗎?')) return;
selectedCategoryIds = [];
selectedProductIds = [];
randomProductsForSelection = [];
firstSubmitDone = false;
btnClose.style.display = 'none';
goToStep(1);
}
// 送出喜好,POST JSON至後端 API
async function submitSelections(){
if(selectedCategoryIds.length !== N){
alert(`請選擇 ${N} 個類別`);
return;
}
if(selectedProductIds.length !== N){
alert(`請選擇 ${N} 件商品`);
return;
}
const payload = {
selectedCategoryIds: selectedCategoryIds,
selectedProductIds: selectedProductIds
};
try {
const res = await fetch(window.location.origin + '/category/update_favorite_categories_products', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload),
credentials: 'same-origin' // 跨站點 cookie,如有需要
});
if(!res.ok){
// 可嘗試解析錯誤訊息
const errorData = await res.json().catch(()=>null);
alert('送出失敗: ' + (errorData?.error || res.statusText));
return;
}
const result = await res.json();
if(result.status === 'success'){
alert('喜好已成功送出!');
firstSubmitDone = true;
btnClose.style.display = 'inline-block';
goToStep(4);
} else {
alert('送出時發生錯誤');
}
} catch(e) {
alert('送出失敗: ' + e.message);
}
}
// 更新footer按鈕顯示狀態
function updateFooterButtons(){
btnReset.style.display = 'inline-block';
btnPrev.style.display = currentStep > 1 ? 'inline-block' : 'none';
btnNext.style.display = currentStep < totalSteps ? 'inline-block' : 'none';
btnSubmit.style.display = currentStep === totalSteps ? 'inline-block' : 'none';
btnClose.style.display = firstSubmitDone ? 'inline-block' : 'none';
updateNextButton();
}
// 事件綁定
btnOpen.addEventListener('click', openModal);
btnReset.addEventListener('click', resetAll);
btnPrev.addEventListener('click', () => {
if(currentStep===3){
goToStep(1);
} else if(currentStep===4){
goToStep(3);
}
});
btnNext.addEventListener('click', () => {
if(currentStep===1){
goToStep(2);
} else if(currentStep===3){
goToStep(4);
}
});
btnSubmit.addEventListener('click', submitSelections);
btnClose.addEventListener('click', ()=>{
if(firstSubmitDone){
closeModal();
} else {
alert('請先完成送出才能關閉視窗。');
}
});
modalBackdrop.addEventListener('click', e=>{
if(e.target === modalBackdrop){
if(firstSubmitDone){
closeModal();
} else {
alert('請先完成送出您的喜好後才能關閉視窗。');
}
}
});
document.addEventListener('keydown', e=>{
if(modalBackdrop.classList.contains('favset-modal-show')){
if(e.key==='Escape'){
if(firstSubmitDone){
closeModal();
} else {
alert('請先完成送出您的喜好後才能關閉視窗。');
}
}
}
});
// ----------------------------------------
// 頁面加載時判斷是否需自動彈出視窗
window.addEventListener('DOMContentLoaded', () => {
// 預設不自動打開,除非下方條件通過
// 預期 is_logged_in 與 cat_favorites 變數為全域變數,由後端輸出進來
if(typeof window.is_logged_in !== 'undefined' && typeof window.cat_favorites !== 'undefined'){
if(window.is_logged_in == 1 && window.cat_favorites == -1){
// 用 setTimeout 避免過早開啟導致無法focus
setTimeout(() => {
openModal();
}, 300);
}
}
});
// 對外公開開啟函式(允許從頁面任何位置呼叫)
window.favsetModalOpen = openModal;
})();
使用說明
後端輸出兩個全域JS變數 :
在PHP檔模板<head>或 <body>任意位置放入:
html Copy code
<script>
window.is_logged_in = <?= (int)$is_logged_in ?>;
window.cat_favorites = <?= (int)$cat_favorites ?>;
</script>
該腳本放置於頁尾或可執行位置 ,完整並正確初始化DOM節點
彈窗會在使用者登入且尚未提交( cat_favorites == -1)時自動開啟,否則顯示開啟按鈕
可從任何地方用:
js Copy code
favsetModalOpen();
輕鬆手動開啟喜好設定彈窗
送出時,資料會POST到 category/update_favorite_categories_products
(需確認路徑無誤且支援此CORS或同源要求)
首次送出前無法關閉 modal,送出成功後可關閉
以上是基於您提供後端API及需求整合的前端JavaScript程式碼。
若有需要,也可協助整合與修改HTML及CSS!
祝開發順利 :)