You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现页面初始仅展示特色项而非全部内容?

解决方案

要实现页面加载时只展示id为feature的分类内容,只需在现有代码基础上添加初始化过滤逻辑即可,不用去修改元素的all类(移除all类会导致你的选择器document.querySelectorAll('.all')抓不到对应元素,反而出问题)。

修改步骤:

  • 页面加载完成后,主动触发一次针对feature分类的过滤操作,同时把对应的分类标题设为激活状态。

修改后的完整代码:

const categoryTitle = document.querySelectorAll('.category-title');
const allCategoryPosts = document.querySelectorAll('.all');

for(let i = 0; i < categoryTitle.length; i++){
    categoryTitle[i].addEventListener('click', filterPosts.bind(this, categoryTitle[i]));
}

function filterPosts(item){
    changeActivePosition(item);
    for(let i = 0; i < allCategoryPosts.length; i++){
        if(allCategoryPosts[i].classList.contains(item.attributes.id.value)){
            allCategoryPosts[i].style.display = "block";
        } else {
            allCategoryPosts[i].style.display = "none";
        }
    }
}

function changeActivePosition(activeItem){
    for(let i = 0; i < categoryTitle.length; i++){
        categoryTitle[i].classList.remove('active');
    }
    activeItem.classList.add('active');
};

// 新增:页面初始化时默认过滤feature分类
const defaultActiveTitle = document.getElementById('feature');
if(defaultActiveTitle) {
    filterPosts(defaultActiveTitle);
}

说明:

  1. 新增的代码会在页面加载完成后,找到id为feature的分类标题元素,调用filterPosts函数,自动执行一次过滤逻辑,这样页面一开始就只会显示带有feature类的内容。
  2. 保留所有元素的all类,因为你的代码是通过这个类来获取所有可过滤的项,移除它会导致对应项无法被筛选控制。

内容的提问来源于stack exchange,提问作者byk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:52:45