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

WordPress点击图标打开滑动面板如何展示对应匹配内容

问题核心原因

  • 页面DOM的id属性必须全局唯一,你在服务列表循环中重复给滑入面板设置了id="slide",浏览器执行document.getElementById("slide")时永远只会返回第一个匹配的元素,因此无论点击哪个图标都只展示第一条内容
  • 点击图标调用的openNav()没有传递当前图标的对应标识,无法匹配到对应的服务内容

修复方案

第一步:调整PHP模板结构

将滑入面板移出循环,全局仅保留1个,循环内仅输出图标和对应的隐藏内容容器,避免重复生成多余的滑入面板:

<?php
$services_query = new WP_Query( array(
    'post_type' => 'servicespage',
    'posts_per_page' => -1,
    'order'   => 'ASC',
    'orderby' => 'menu_order'
    )
);
?>

<?php if ( $services_query->have_posts() ) : ?>
    <?php while ( $services_query->have_posts() ) : $services_query->the_post(); ?> 
        <?php $current_id = get_the_ID(); ?>

        <!-- 图标区域 -->
        <div class="icon" onclick="openNav(<?php echo $current_id; ?>)" data-src="content-<?php echo $current_id ?>">             
            <?php if (has_post_thumbnail( $post->ID ) ): ?>
                <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
                <img src="<?php echo $image[0]; ?>">     
            <?php endif; ?>
            <h3><?php the_title(); ?></h3>  
        </div>

        <!-- 对应服务内容(默认隐藏) -->
        <div id="content-<?php echo $current_id ?>" class="service-content" style="display:none;">    
            <div class="test">
                <h3><?php the_title(); ?></h3>      
                <?php the_content(); ?>     
            </div>
        </div>

    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
<?php endif; ?>             

<!-- 全局唯一的滑入面板 -->
<div id="slide" class="overlay">    
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <div id="slide-content-wrap"></div>
</div>

第二步:修改JS交互逻辑

修改openNav方法,接收传入的服务ID,将对应内容渲染到滑入面板后再展开:

// 打开滑入面板
function openNav(serviceId) {
    // 拿到对应服务的内容
    const targetContent = document.getElementById(`content-${serviceId}`).innerHTML;
    // 将内容插入滑入面板的容器
    document.getElementById('slide-content-wrap').innerHTML = targetContent;
    // 展开滑入面板
    document.getElementById("slide").style.width = "100%";
}

// 关闭滑入面板
function closeNav() {
    document.getElementById("slide").style.width = "0%";
    // 可选:关闭时清空内容,避免闪现旧内容
    setTimeout(() => {
        document.getElementById('slide-content-wrap').innerHTML = '';
    }, 300); // 300ms和你的滑入动画时长保持一致即可
}

如果不想调整结构,也可以给每个循环中的滑入面板加上唯一ID,比如id="slide-<?php echo $current_id; ?>",然后openNav直接操作对应ID的面板展开即可,不过全局仅保留1个滑入面板的方案性能更好,不会生成多余DOM节点。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:06:08