98 lines
3.6 KiB
JavaScript
98 lines
3.6 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function() {
|
||
// 获取URL参数中的产品ID
|
||
const urlParams = new URLSearchParams(window.location.search);
|
||
const productId = urlParams.get('product');
|
||
|
||
// 显示产品的函数
|
||
function showProduct(productId, shouldScroll = false) { // 默认不滚动
|
||
console.log('Showing product:', productId);
|
||
|
||
// 移除所有产品项的active类
|
||
const productItems = document.querySelectorAll('.product-item');
|
||
productItems.forEach(p => {
|
||
p.classList.remove('active');
|
||
});
|
||
|
||
// 找到对应的产品项并添加active类
|
||
const targetItem = document.querySelector(`[data-product="${productId}"]`);
|
||
if (targetItem) {
|
||
targetItem.classList.add('active');
|
||
|
||
// 确保产品所在的分类是展开的
|
||
const category = targetItem.closest('.category-content');
|
||
if (category) {
|
||
// 先移除所有分类的show类
|
||
document.querySelectorAll('.category-content').forEach(c => {
|
||
c.classList.remove('show');
|
||
});
|
||
document.querySelectorAll('.category-header').forEach(h => {
|
||
h.classList.remove('active');
|
||
});
|
||
|
||
// 展开当前分类
|
||
category.classList.add('show');
|
||
const categoryHeader = category.previousElementSibling;
|
||
if (categoryHeader) {
|
||
categoryHeader.classList.add('active');
|
||
}
|
||
}
|
||
|
||
// 隐藏所有详情内容
|
||
document.querySelectorAll('.detail-content').forEach(content => {
|
||
if (content) {
|
||
content.style.display = 'none';
|
||
}
|
||
});
|
||
|
||
// 显示目标产品详情
|
||
const targetContent = document.getElementById(productId);
|
||
if (targetContent) {
|
||
targetContent.style.display = 'block';
|
||
}
|
||
|
||
// 只在指定需要滚动时才滚动
|
||
if (shouldScroll) {
|
||
setTimeout(() => {
|
||
targetItem.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||
}, 100);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 初始化:根据URL参数决定行为
|
||
if (productId) {
|
||
// 如果有产品ID参数,则显示对应产品并滚动
|
||
showProduct(productId, true); // 有参数时滚动
|
||
} else {
|
||
// 没有参数时,显示第一个产品但不滚动
|
||
const firstProduct = document.querySelector('.product-item');
|
||
if (firstProduct) {
|
||
showProduct(firstProduct.dataset.product, false); // 无参数时不滚动
|
||
}
|
||
}
|
||
|
||
// 产品项点击处理
|
||
const productItems = document.querySelectorAll('.product-item');
|
||
productItems.forEach(item => {
|
||
item.addEventListener('click', function() {
|
||
const productId = this.dataset.product;
|
||
// 点击产品项时需要滚动
|
||
showProduct(productId, true);
|
||
updateURL(productId);
|
||
});
|
||
});
|
||
|
||
// 更新URL函数
|
||
function updateURL(productId) {
|
||
const newURL = new URL(window.location.href);
|
||
newURL.searchParams.set('product', productId);
|
||
window.history.pushState({ productId }, '', newURL);
|
||
}
|
||
|
||
// 处理浏览器后退/前进
|
||
window.addEventListener('popstate', function(event) {
|
||
if (event.state && event.state.productId) {
|
||
showProduct(event.state.productId, true);
|
||
}
|
||
});
|
||
}); |