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

如何用Vanilla JavaScript基于当前日期动态排序可折叠内容?

动态排列季节性板块的Vanilla JavaScript实现

实现思路

核心逻辑是根据当前月份确定板块顺序,再重新排列DOM元素,步骤如下:

  1. 获取当前月份(转换为1-12的实际月份)
  2. 匹配对应季节的板块顺序规则
  3. 按规则重新将板块追加到容器中

代码实现

HTML结构示例

假设你的折叠板块放在一个容器内,每个板块通过data-section标识类型:

<div id="section-container">
  <!-- Agriculture板块 -->
  <div class="collapsible-section" data-section="agriculture">
    <h3>Agriculture(土壤温度与湿度)</h3>
    <!-- 板块内容 -->
  </div>
  <!-- Freeze Dates板块 -->
  <div class="collapsible-section" data-section="freeze">
    <h3>Freeze Dates</h3>
    <!-- 板块内容 -->
  </div>
  <!-- Snowfall板块 -->
  <div class="collapsible-section" data-section="snowfall">
    <h3>Snowfall</h3>
    <!-- 板块内容 -->
  </div>
</div>

JavaScript代码

将以下代码放在页面底部,或包裹在DOMContentLoaded事件中确保DOM加载完成:

// 获取当前月份(getMonth()返回0-11,+1转为1-12)
const currentMonth = new Date().getMonth() + 1;

// 根据月份确定板块顺序
let sectionOrder;
if (currentMonth >= 3 && currentMonth <= 8) {
  sectionOrder = ['agriculture', 'freeze', 'snowfall'];
} else if (currentMonth >= 9 && currentMonth <= 11) {
  sectionOrder = ['freeze', 'snowfall', 'agriculture'];
} else {
  sectionOrder = ['snowfall', 'freeze', 'agriculture'];
}

// 获取容器和所有板块元素
const container = document.getElementById('section-container');
const sections = Array.from(container.querySelectorAll('[data-section]'));

// 按顺序重新排列板块
sectionOrder.forEach(sectionKey => {
  const targetSection = sections.find(section => section.dataset.section === sectionKey);
  if (targetSection) {
    container.appendChild(targetSection);
  }
});

关键说明

  • data-section属性用于精准匹配板块,确保JS能正确识别每个板块类型
  • 使用appendChild()重新排列时,已存在的DOM元素会被移动到容器末尾,不会重复创建
  • 如果你的板块用id标识而非data-section,可以将代码中的dataset.section替换为id,同时调整sectionOrder的对应值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:25:30