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

如何在Divi中实现点击元素切换另一元素的显示与隐藏?

点击标题切换内容区域的显示/隐藏(Divi框架适配)

需求说明

点击<h2 class="entry-title">元素时,切换<div class="post-content">的显示与隐藏,无法直接编辑HTML,仅可添加CSS和JavaScript。

参考HTML结构

<article id="post-301">
    <h2 class="entry-title">Best Practices</h2>
    <div class="post-content">
        <div class="post-content-inner et_pb_blog_show_content">
            <p>The ten central child protection steps through which organizations will progress as part of the Aleinu campaign.</p>
        </div>
    </div>            
</article>

原脚本问题分析

你之前的脚本存在几个关键错误:

  • getElementsByClassName参数不需要加.,正确写法为getElementsByClassName("post-content")
  • 该方法返回元素集合,不能直接访问.style属性,需指定索引(如x[0])
  • 混用jQuery与原生JS语法,逻辑混乱
  • 末尾多了一个冗余的闭合括号)

修正后的解决方案

步骤1:添加CSS(可选,设置初始隐藏状态)

若需要默认隐藏内容区域,添加以下CSS:

.post-content {
    display: none;
}

步骤2:添加正确的jQuery脚本

利用Divi自带的jQuery,用简洁语法实现切换:

jQuery(function($) {
    // 页面加载完成后绑定事件,兼容动态渲染元素
    $(document).on('click', '.entry-title', function() {
        // 定位当前标题同级的内容区域,切换显示状态
        $(this).siblings('.post-content').toggle();
    });
});

脚本说明

  • $(document).on绑定事件,确保Divi动态生成的元素也能触发效果
  • $(this).siblings('.post-content')精准定位目标内容,避免影响其他文章
  • .toggle()方法自动切换元素显示/隐藏状态,无需手动判断display属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:50:19