我正開發一個網上商店的篩選功能,現功能整體已完成,但我想做到以下效果:… · The Chat Archive
明白你的需求,以下是一個完整的範例,示範如何從URL的Query Params讀取所有篩選條件,並將它們以「條件名稱: 數值」的格式顯示在畫面上,且條件名稱會做轉換為較可讀的文字。
主要功能說明:
利用 URLSearchParams 解析 URL 參數。
預設會將key做簡單的映射轉換(例如 min-price 轉為「最低價格」)。
將所有參數列出來並呈現在頁面某個區域。
範例程式碼:
html Copy code
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>篩選條件顯示</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
background: #f5f5f5;
}
.filter-conditions {
background: white;
border-radius: 8px;
padding: 15px 20px;
max-width: 400px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.filter-conditions h2 {
margin-top: 0;
font-size: 1.5em;
border-bottom: 2px solid #333;
padding-bottom: 6px;
}
.filter-item {
margin: 8px 0;
font-size: 1.1em;
color: #333;
}
</style>
</head>
<body>
<div class="filter-conditions" id="filterConditions">
<h2>當前篩選條件</h2>
<!-- 篩選條件列表會由JS注入這裡 -->
</div>
<script>
// key to readable name mapping
const keyNameMap = {
'min-price': '最低價格',
'max-price': '最高價格',
'min-rating': '最低評分',
'max-rating': '最高評分',
'filter-分類': '分類',
// 如需更多對應請自行加
};
function decodeParamValue(value) {
try {
// 對可能的URL編碼做解碼(但URLSearchParams一般已自動解碼)
return decodeURIComponent(value);
} catch {
return value;
}
}
function getReadableKey(key) {
// 先嘗試直接轉換
if (keyNameMap[key]) {
return keyNameMap[key];
}
// 嘗試部分匹配如 "filter-分類" => "分類"
for (let mapKey in keyNameMap) {
if (key.startsWith(mapKey)) {
return keyNameMap[mapKey];
}
}
// 如果沒有匹配到就直接用key,但將 - 改成空格並大寫第一字
return key.replace(/-/g, ' ').replace(/^./, str => str.toUpperCase());
}
function renderFilters() {
const container = document.getElementById('filterConditions');
const params = new URLSearchParams(window.location.search);
if (!params.toString()) {
container.insertAdjacentHTML('beforeend', `<div class="filter-item">目前無篩選條件</div>`);
return;
}
params.forEach((value, key) => {
// 針對你的範例filter-分類可能是用pipe分割多個值,可做額外處理
let displayValue = decodeParamValue(value);
// 你範例的filter-分類值是用 | 分隔,我這邊幫你換成中文逗號顯示
if (key.startsWith('filter-')) {
displayValue = displayValue.split('|').join('、');
}
const readableKey = getReadableKey(key);
const itemHtml = `<div class="filter-item">${readableKey}: ${displayValue}</div>`;
container.insertAdjacentHTML('beforeend', itemHtml);
});
}
// 頁面載入完成後執行
window.addEventListener('DOMContentLoaded', renderFilters);
</script>
</body>
</html>
使用說明:
這樣你就可以輕鬆取得URL搜尋參數,並將篩選條件轉成更可讀的格式顯示在畫面上。如果有其他特別的key要對應,可以在 keyNameMap 裡加入。
請將所有element的class及id 加上.new-filter-modal的前綴,以免與其他樣式發生衝突
Assistant2025-07-14 01:57 UTC Copy response
明白,你希望所有的 class 及 id 都加上前綴 .new-filter-modal,以避免樣式和id衝突。下面是修改後的完整範例,已將 class 和 id 名稱前面加上 new-filter-modal-,並將 CSS 選擇器對應改成以 .new-filter-modal 父容器為範圍以避免全局污染。
修改後程式碼
html Copy code
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>篩選條件顯示</title>
<style>
/* 父容器避免全局影響 */
.new-filter-modal {
font-family: Arial, sans-serif;
padding: 20px;
background: #f5f5f5;
max-width: 420px;
}
.new-filter-modal-new-filter-modal-filter-conditions {
background: white;
border-radius: 8px;
padding: 15px 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.new-filter-modal-new-filter-modal-filter-conditions h2 {
margin-top: 0;
font-size: 1.5em;
border-bottom: 2px solid #333;
padding-bottom: 6px;
}
.new-filter-modal-new-filter-modal-filter-item {
margin: 8px 0;
font-size: 1.1em;
color: #333;
}
</style>
</head>
<body>
<!-- 父容器class有前綴,可作為所有子元素的範圍 -->
<div class="new-filter-modal">
<div class="new-filter-modal-new-filter-modal-filter-conditions" id="new-filter-modal-filterConditions">
<h2>當前篩選條件</h2>
<!-- 篩選條件列表會由JS注入這裡 -->
</div>
</div>
<script>
// key to readable name mapping
const keyNameMap = {
'min-price': '最低價格',
'max-price': '最高價格',
'min-rating': '最低評分',
'max-rating': '最高評分',
'filter-分類': '分類',
// 如需更多對應請自行加
};
function decodeParamValue(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function getReadableKey(key) {
if (keyNameMap[key]) {
return keyNameMap[key];
}
for (let mapKey in keyNameMap) {
if (key.startsWith(mapKey)) {
return keyNameMap[mapKey];
}
}
return key.replace(/-/g, ' ').replace(/^./, str => str.toUpperCase());
}
function renderFilters() {
// 新ID對應改寫
const container = document.getElementById('new-filter-modal-filterConditions');
const params = new URLSearchParams(window.location.search);
if (!params.toString()) {
container.insertAdjacentHTML(
'beforeend',
`<div class="new-filter-modal-new-filter-modal-filter-item">目前無篩選條件</div>`
);
return;
}
params.forEach((value, key) => {
let displayValue = decodeParamValue(value);
if (key.startsWith('filter-')) {
displayValue = displayValue.split('|').join('、');
}
const readableKey = getReadableKey(key);
const itemHtml = `<div class="new-filter-modal-new-filter-modal-filter-item">${readableKey}: ${displayValue}</div>`;
container.insertAdjacentHTML('beforeend', itemHtml);
});
}
window.addEventListener('DOMContentLoaded', renderFilters);
</script>
</body>
</html>
能修改範例以讀取變數中的URL文字,而非當前頁面?或保留獲取當前頁面連結的方法
Assistant2025-07-14 02:00 UTC Copy response
當然可以!你想要的功能是:
透過「變數中的URL字串」來解析參數並顯示,
同時又保留從「當前頁面URL」讀取參數的功能。
我這裡示範一個折衷作法,讓你可以設定一個可選的變數 inputUrl (字串)。如果該變數有值,會從那裡取參數;如果沒有,會從目前頁面URL取得參數。
修改後完整範例
請更改篩選顯示變為插件,並以圓邊Tag表示一個條件,如分類多於一個,需拆分成獨立的tag。
並加入可刪除tag的function,當用戶按下Tag旁的刪除按鈕('x'),將會從URL中移除該條件,並以刪除後的條件重載頁面
Assistant2025-07-14 02:12 UTC Copy response
了解你的需求:
將篩選條件顯示改成一個插件 (component)形式,方便獨立使用。
每個條件以圓邊 Tag 呈現,一個tag代表一個篩選項目(如果分類是多值,拆分成多個tag)。
每個tag旁有刪除按鈕(×),點擊後會從 URL 中移除對應條件,然後刷新頁面。
這裡給你一個可直接使用的 自包含 篩選條件tag插件範例
Show full message · 208 lines 能修改範例以讀取變數中的URL文字,而非當前頁面?或保留獲取當前頁面連結的方法
Assistant2025-07-14 02:14 UTC Copy response
當然可以!我已將範例改寫成支援:
可指定一個URL字串變數 ,從該URL解析參數並顯示Tag。
若該變數為空(或未設定),則自動使用當前頁面URL參數。
而且刪除Tag時,會重新建構新URL字串並重新導向(刷新)此URL。
以下是修改後的完整範例:
Show full message · 202 lines 針對價格,請加入前綴HK$
Tag的背景顏色改為: #121535, 文字顏色改為: white
刪除的按鈕應垂直置中至整個Tag,以及改用較好的關閉icon
Assistant2025-07-14 02:19 UTC Copy response
了解你需求,針對「價格Tag」加上前綴 HK$ ,並調整Tag背景色與文字色、刪除按鈕垂直置中及改良關閉圖示。
以下是更新後的完整範例:
Show full message · 255 lines Not yet included in a published release.
變動重點:
父容器增加 .new-filter-modal class 包裹所有元素,方便限定CSS作用範圍。
對所有原本的 class 名稱 及 id 增加前綴 new-filter-modal-,避免和外層頁面或其他元件衝突。
CSS 選擇器也改成在 .new-filter-modal 內部作用。
這樣整體的樣式和識別不會影響或被其他部分污染,適合多模組或大型專案避免衝突。若你還有其他需求,歡迎隨時提出!
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>篩選條件顯示</title>
<style>
.new-filter-modal {
font-family: Arial, sans-serif;
padding: 20px;
background: #f5f5f5;
max-width: 420px;
}
.new-filter-modal-new-filter-modal-filter-conditions {
background: white;
border-radius: 8px;
padding: 15px 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.new-filter-modal-new-filter-modal-filter-conditions h2 {
margin-top: 0;
font-size: 1.5em;
border-bottom: 2px solid #333;
padding-bottom: 6px;
}
.new-filter-modal-new-filter-modal-filter-item {
margin: 8px 0;
font-size: 1.1em;
color: #333;
}
</style>
</head>
<body>
<div class="new-filter-modal">
<div class="new-filter-modal-new-filter-modal-filter-conditions" id="new-filter-modal-filterConditions">
<h2>當前篩選條件</h2>
<!-- 篩選條件列表由JS注入 -->
</div>
</div>
<script>
const keyNameMap = {
'min-price': '最低價格',
'max-price': '最高價格',
'min-rating': '最低評分',
'max-rating': '最高評分',
'filter-分類': '分類',
};
function decodeParamValue(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function getReadableKey(key) {
if (keyNameMap[key]) {
return keyNameMap[key];
}
for (let mapKey in keyNameMap) {
if (key.startsWith(mapKey)) {
return keyNameMap[mapKey];
}
}
return key.replace(/-/g, ' ').replace(/^./, str => str.toUpperCase());
}
function renderFiltersFromParams(params) {
const container = document.getElementById('new-filter-modal-filterConditions');
// 清空內容(保留標題h2)
container.querySelectorAll('.new-filter-modal-new-filter-modal-filter-item').forEach(el => el.remove());
if (!params.toString()) {
container.insertAdjacentHTML(
'beforeend',
`<div class="new-filter-modal-new-filter-modal-filter-item">目前無篩選條件</div>`
);
return;
}
params.forEach((value, key) => {
let displayValue = decodeParamValue(value);
if (key.startsWith('filter-')) {
displayValue = displayValue.split('|').join('、');
}
const readableKey = getReadableKey(key);
const itemHtml = `<div class="new-filter-modal-new-filter-modal-filter-item">${readableKey}: ${displayValue}</div>`;
container.insertAdjacentHTML('beforeend', itemHtml);
});
}
function renderFilters() {
// 這裡設置你要讀取的URL字串(模擬)
// 若設成空字串或 null,會自動使用當前頁面URL
const inputUrl = ''; // 例如: "https://example.com/products/search?filter-%E5%88%86%E9%A1%9E=%E9%95%B7%E8%80%85%7C%E9%A3%B2%E5%93%81&min-price=0&max-price=260000"
let params;
if (inputUrl) {
try {
// 從變數URL解析searchParams
const urlObj = new URL(inputUrl);
params = urlObj.searchParams;
} catch (e) {
console.error('輸入的URL格式錯誤,改為使用當前頁面URL');
params = new URLSearchParams(window.location.search);
}
} else {
// 不指定URL,使用當前頁面URL參數
params = new URLSearchParams(window.location.search);
}
renderFiltersFromParams(params);
}
window.addEventListener('DOMContentLoaded', renderFilters);
</script>
</body>
</html>
使用說明:
你可以在變數 inputUrl 設定你想解析的完整URL字串(範例有註解),就會讀取該字串中的參數進行顯示。
若 inputUrl 是空字串或 null,則會自動用瀏覽器當前頁面的URL解析並顯示篩選條件。
這樣你同時擁有兩種方式:變數URL讀取,或當前頁面URL讀取。
若要測試,請將 inputUrl 變數改成你想模擬的任意URL字串(包含 ? 後的Query部分),再重新整理就會用該網址參數。
如果沒有指定 inputUrl,網頁自動抓當前網址參數。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>篩選條件 Tag 插件</title>
<style>
.new-filter-modal {
font-family: Arial, sans-serif;
padding: 20px;
background: #f9f9f9;
max-width: 500px;
}
.new-filter-modal-filter-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
/* Tag 樣式 */
.new-filter-modal-filter-tag {
display: inline-flex;
align-items: center;
background-color: #e0e7ff;
color: #1e3a8a;
border-radius: 9999px; /* 完全圓邊 */
padding: 6px 12px;
font-size: 0.9em;
user-select: none;
cursor: default;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.new-filter-modal-filter-tag .delete-btn {
display: inline-flex;
margin-left: 8px;
font-weight: bold;
cursor: pointer;
user-select: none;
color: #1e3a8a;
border-radius: 50%;
width: 18px;
height: 18px;
justify-content: center;
align-items: center;
transition: background-color 0.2s;
}
.new-filter-modal-filter-tag .delete-btn:hover {
background-color: #c7d2fe;
}
</style>
</head>
<body>
<div class="new-filter-modal">
<h2>當前篩選條件</h2>
<div id="new-filter-modal-filterTags" class="new-filter-modal-filter-tags"></div>
</div>
<script>
(function() {
const keyNameMap = {
'min-price': '最低價格',
'max-price': '最高價格',
'min-rating': '最低評分',
'max-rating': '最高評分',
'filter-分類': '分類',
};
function decodeParamValue(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function getReadableKey(key) {
if (keyNameMap[key]) return keyNameMap[key];
for (let mapKey in keyNameMap) {
if (key.startsWith(mapKey)) return keyNameMap[mapKey];
}
// 沒匹配則簡單格式化
return key.replace(/-/g, ' ').replace(/^./, str => str.toUpperCase());
}
/**
* 將URL中的參數解析成一個[ {key, value} ]的扁平陣列
* 如果是filter-分類這類多值,用分隔符拆開並分成多個item。
*/
function parseParamsToTags(params) {
const tags = [];
params.forEach((value, key) => {
const readableKey = getReadableKey(key);
if (key.startsWith('filter-')) {
// 多值拆分,支援你的分隔符 "|"
const values = value.split('|').map(v => decodeParamValue(v));
values.forEach(val => {
tags.push({ key, value: val, displayKey: readableKey });
});
} else {
tags.push({ key, value: decodeParamValue(value), displayKey: readableKey });
}
});
return tags;
}
/**
* 從URLSearchParams移除一個 key-value 篩選條件
* 針對多值欄位刪除單一value,有值就刪value,有keyValue就刪一個item或整個key
*/
function removeTagFromParams(params, tag) {
if (tag.key.startsWith('filter-')) {
// 多值的欄位,拆開刪除對應value
const vals = params.get(tag.key).split('|').filter(v => decodeURIComponent(v) !== tag.value);
if (vals.length === 0) {
params.delete(tag.key);
} else {
params.set(tag.key, vals.join('|'));
}
} else {
// 單一值欄位,直接刪除該key
params.delete(tag.key);
}
}
/**
* 渲染Tag至頁面並綁定刪除事件
*/
function renderTags(tags) {
const container = document.getElementById('new-filter-modal-filterTags');
container.innerHTML = ''; // 先清空
if (tags.length === 0) {
container.innerHTML = '<div>目前無篩選條件</div>';
return;
}
tags.forEach(tag => {
const tagEl = document.createElement('div');
tagEl.className = 'new-filter-modal-filter-tag';
// 文字格式: 條件名稱: 值
tagEl.textContent = `${tag.displayKey}: ${tag.value}`;
// 創建刪除按鈕
const delBtn = document.createElement('span');
delBtn.className = 'delete-btn';
delBtn.textContent = '×';
delBtn.title = '刪除此條件';
delBtn.addEventListener('click', () => {
// 從URL移除該條件並重載
const currentParams = new URLSearchParams(window.location.search);
removeTagFromParams(currentParams, tag);
// 重新組成URL並reload
const baseUrl = window.location.origin + window.location.pathname;
const newSearch = currentParams.toString();
window.location.href = newSearch ? baseUrl + '?' + newSearch : baseUrl;
});
tagEl.appendChild(delBtn);
container.appendChild(tagEl);
});
}
function initFilterTagPlugin() {
const params = new URLSearchParams(window.location.search);
const tags = parseParamsToTags(params);
renderTags(tags);
}
window.addEventListener('DOMContentLoaded', initFilterTagPlugin);
})();
</script>
</body>
</html>
功能說明
整個篩選 Tag 顯示與操作是封裝在立即執行函式內,作為一個獨立插件。
所有CSS和元素class皆加上 .new-filter-modal- 前綴,避免樣式污染。
會自動從 URL 讀取參數,拆分多值的分類,顯示為多個Tag。
每個Tag有刪除按鈕,點按會從 URL 移除該條件後,自動刷新頁面(帶新的條件)。
針對多值「filter-分類」,刪除只會移除點擊的單一值,其他值保持。
針對單一值參數(例如 min-price,max-price)刪除會移除整個參數。
你可以依此自行擴展更多key的對應(keyNameMap),或調整CSS樣式使外觀更合適。 如果需要改為AJAX更新條件而非刷新頁面,也可以提供範例,隨時告訴我!
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>篩選條件 Tag 插件 (可指定URL字串)</title>
<style>
.new-filter-modal {
font-family: Arial, sans-serif;
padding: 20px;
background: #f9f9f9;
max-width: 500px;
}
.new-filter-modal-filter-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
/* Tag 樣式 */
.new-filter-modal-filter-tag {
display: inline-flex;
align-items: center;
background-color: #e0e7ff;
color: #1e3a8a;
border-radius: 9999px;
padding: 6px 12px;
font-size: 0.9em;
user-select: none;
cursor: default;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.new-filter-modal-filter-tag .delete-btn {
display: inline-flex;
margin-left: 8px;
font-weight: bold;
cursor: pointer;
user-select: none;
color: #1e3a8a;
border-radius: 50%;
width: 18px;
height: 18px;
justify-content: center;
align-items: center;
transition: background-color 0.2s;
}
.new-filter-modal-filter-tag .delete-btn:hover {
background-color: #c7d2fe;
}
</style>
</head>
<body>
<div class="new-filter-modal">
<h2>當前篩選條件</h2>
<div id="new-filter-modal-filterTags" class="new-filter-modal-filter-tags"></div>
</div>
<script>
(function() {
const keyNameMap = {
'min-price': '最低價格',
'max-price': '最高價格',
'min-rating': '最低評分',
'max-rating': '最高評分',
'filter-分類': '分類',
};
function decodeParamValue(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function getReadableKey(key) {
if (keyNameMap[key]) return keyNameMap[key];
for (let mapKey in keyNameMap) {
if (key.startsWith(mapKey)) return keyNameMap[mapKey];
}
return key.replace(/-/g, ' ').replace(/^./, str => str.toUpperCase());
}
function parseParamsToTags(params) {
const tags = [];
params.forEach((value, key) => {
const readableKey = getReadableKey(key);
if (key.startsWith('filter-')) {
const values = value.split('|').map(v => decodeParamValue(v));
values.forEach(val => {
tags.push({ key, value: val, displayKey: readableKey });
});
} else {
tags.push({ key, value: decodeParamValue(value), displayKey: readableKey });
}
});
return tags;
}
function removeTagFromParams(params, tag) {
if (tag.key.startsWith('filter-')) {
const vals = params.get(tag.key).split('|').filter(v => decodeURIComponent(v) !== tag.value);
if (vals.length === 0) {
params.delete(tag.key);
} else {
params.set(tag.key, vals.join('|'));
}
} else {
params.delete(tag.key);
}
}
function renderTags(tags, params, baseUrl) {
const container = document.getElementById('new-filter-modal-filterTags');
container.innerHTML = '';
if (tags.length === 0) {
container.innerHTML = '<div>目前無篩選條件</div>';
return;
}
tags.forEach(tag => {
const tagEl = document.createElement('div');
tagEl.className = 'new-filter-modal-filter-tag';
tagEl.textContent = `${tag.displayKey}: ${tag.value}`;
const delBtn = document.createElement('span');
delBtn.className = 'delete-btn';
delBtn.textContent = '×';
delBtn.title = '刪除此條件';
delBtn.addEventListener('click', () => {
removeTagFromParams(params, tag);
const newSearch = params.toString();
window.location.href = newSearch ? baseUrl + '?' + newSearch : baseUrl;
});
tagEl.appendChild(delBtn);
container.appendChild(tagEl);
});
}
function initFilterTagPlugin() {
// --------- 這是你可以修改的URL字串變數 ---------
const inputUrl = ''; // 空字串表示不指定URL,用當前頁面URL;可改成完整url字串測試
// -------------------------------------------------
let params, baseUrl;
if (inputUrl) {
try {
const urlObj = new URL(inputUrl);
params = new URLSearchParams(urlObj.search);
baseUrl = urlObj.origin + urlObj.pathname;
} catch (e) {
console.error('輸入的URL格式錯誤,改用當前頁面URL');
params = new URLSearchParams(window.location.search);
baseUrl = window.location.origin + window.location.pathname;
}
} else {
params = new URLSearchParams(window.location.search);
baseUrl = window.location.origin + window.location.pathname;
}
const tags = parseParamsToTags(params);
renderTags(tags, params, baseUrl);
}
window.addEventListener('DOMContentLoaded', initFilterTagPlugin);
})();
</script>
</body>
</html>
使用建議:
修改 const inputUrl = '' 為你想模擬的完整網址(例如 "https://example.com/products/search?filter-%E5%88%86%E9%A1%9E=長者|飲品&min-price=0")會使用該URL參數顯示條件。
或保持空字串 '',就會自動從當前頁面URL抓條件。
點擊Tag的 × 按鈕會移除該條件並刷新頁面到更新後的URL。
若要用Ajax動態更新而不刷新頁面,或是其它要求,也都可以再跟我說!
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>篩選條件 Tag 插件 (價格加HK$,自訂樣式)</title>
<style>
.new-filter-modal {
font-family: Arial, sans-serif;
padding: 20px;
background: #f9f9f9;
max-width: 500px;
}
.new-filter-modal-filter-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
/* Tag 樣式 */
.new-filter-modal-filter-tag {
display: inline-flex;
align-items: center; /* 垂直置中 */
background-color: #121535;
color: white;
border-radius: 9999px; /* 完全圓邊 */
padding: 6px 12px;
font-size: 0.9em;
user-select: none;
cursor: default;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}
/* 刪除按鈕 */
.new-filter-modal-filter-tag .delete-btn {
display: inline-flex;
margin-left: 8px;
cursor: pointer;
user-select: none;
color: white;
border-radius: 50%;
width: 18px;
height: 18px;
justify-content: center;
align-items: center;
transition: background-color 0.2s;
flex-shrink: 0;
}
.new-filter-modal-filter-tag .delete-btn:hover {
background-color: rgba(255 255 255 / 0.2);
}
/* 關閉圖示SVG */
.new-filter-modal-filter-tag .delete-btn svg {
width: 12px;
height: 12px;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
</style>
</head>
<body>
<div class="new-filter-modal">
<h2>當前篩選條件</h2>
<div id="new-filter-modal-filterTags" class="new-filter-modal-filter-tags"></div>
</div>
<script>
(function() {
const keyNameMap = {
'min-price': '最低價格',
'max-price': '最高價格',
'min-rating': '最低評分',
'max-rating': '最高評分',
'filter-分類': '分類',
};
function decodeParamValue(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function getReadableKey(key) {
if (keyNameMap[key]) return keyNameMap[key];
for (let mapKey in keyNameMap) {
if (key.startsWith(mapKey)) return keyNameMap[mapKey];
}
return key.replace(/-/g, ' ').replace(/^./, str => str.toUpperCase());
}
// 價格前綴文字函式
function formatDisplayValue(key, value) {
// 判斷是否價格欄位
if (key === 'min-price' || key === 'max-price') {
return `HK$${value}`;
}
return value;
}
function parseParamsToTags(params) {
const tags = [];
params.forEach((value, key) => {
const readableKey = getReadableKey(key);
if (key.startsWith('filter-')) {
const values = value.split('|').map(v => decodeParamValue(v));
values.forEach(val => {
tags.push({ key, value: val, displayKey: readableKey });
});
} else {
tags.push({ key, value: decodeParamValue(value), displayKey: readableKey });
}
});
return tags;
}
function removeTagFromParams(params, tag) {
if (tag.key.startsWith('filter-')) {
const vals = params.get(tag.key).split('|').filter(v => decodeURIComponent(v) !== tag.value);
if (vals.length === 0) {
params.delete(tag.key);
} else {
params.set(tag.key, vals.join('|'));
}
} else {
params.delete(tag.key);
}
}
function createCloseIcon() {
// SVG關閉圖示,細緻且常見
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const line1 = document.createElementNS(svgNS, "line");
line1.setAttribute("x1", "18");
line1.setAttribute("y1", "6");
line1.setAttribute("x2", "6");
line1.setAttribute("y2", "18");
const line2 = document.createElementNS(svgNS, "line");
line2.setAttribute("x1", "6");
line2.setAttribute("y1", "6");
line2.setAttribute("x2", "18");
line2.setAttribute("y2", "18");
svg.appendChild(line1);
svg.appendChild(line2);
return svg;
}
function renderTags(tags, params, baseUrl) {
const container = document.getElementById('new-filter-modal-filterTags');
container.innerHTML = '';
if (tags.length === 0) {
container.innerHTML = '<div>目前無篩選條件</div>';
return;
}
tags.forEach(tag => {
const tagEl = document.createElement('div');
tagEl.className = 'new-filter-modal-filter-tag';
const displayVal = formatDisplayValue(tag.key, tag.value);
tagEl.textContent = `${tag.displayKey}: ${displayVal}`;
const delBtn = document.createElement('span');
delBtn.className = 'delete-btn';
delBtn.title = '刪除此條件';
// 插入SVG關閉圖示
delBtn.appendChild(createCloseIcon());
delBtn.addEventListener('click', () => {
removeTagFromParams(params, tag);
const newSearch = params.toString();
window.location.href = newSearch ? baseUrl + '?' + newSearch : baseUrl;
});
tagEl.appendChild(delBtn);
container.appendChild(tagEl);
});
}
function initFilterTagPlugin() {
// 可在此修改模擬URL,空字串用當前頁面URL
const inputUrl = '';
let params, baseUrl;
if (inputUrl) {
try {
const urlObj = new URL(inputUrl);
params = new URLSearchParams(urlObj.search);
baseUrl = urlObj.origin + urlObj.pathname;
} catch (e) {
console.error('輸入的URL格式錯誤,改用當前頁面URL');
params = new URLSearchParams(window.location.search);
baseUrl = window.location.origin + window.location.pathname;
}
} else {
params = new URLSearchParams(window.location.search);
baseUrl = window.location.origin + window.location.pathname;
}
const tags = parseParamsToTags(params);
renderTags(tags, params, baseUrl);
}
window.addEventListener('DOMContentLoaded', initFilterTagPlugin);
})();
</script>
</body>
</html>
修改重點:
**價格前綴HK∗ ∗ :使用 ‘ f o r m a t D i s p l a y V a l u e ‘ 函式,專門判斷 ‘ m i n − p r i c e ‘ 和 ‘ m a x − p r i c e ‘ ,在數字前加上 ‘ H K **:
使用 `formatDisplayValue` 函式,專門判斷 `min-price` 和 `max-price`,在數字前加上 `HK ∗ ∗ :使用 ‘ f or ma t D i s pl a y V a l u e ‘ 函式,專門判斷 ‘ min − p r i ce ‘ 和 ‘ ma x − p r i ce ‘ ,在數字前加上 ‘ H K `。
Tag背景與文字色 :
background-color: #121535; color: white;。
刪除按鈕垂直置中 :
按鈕與文字同在flex容器 .new-filter-modal-filter-tag 中,使用 align-items: center,刪除按鈕設為 flex item 且設定寬高,使icon垂直置中。
刪除按鈕關閉圖示 :
改用SVG繪製細緻的X符號(2條斜線交叉),色彩隨字體顏色(白色)。
你可以直接在瀏覽器打開此頁並於URL帶入篩選參數測試,或修改 inputUrl 變數模擬不同參數。