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

如何让同一图片/按钮双向触发:切换内容显示与恢复初始状态

Solution to Toggle Portfolio Content On/Off with the Same Image

Got it, let's adjust your code so clicking the same portfolio image toggles it back to the initial state (instead of just opening new content). Here's the step-by-step fix:

1. Modify the selectPortfolio JavaScript Function

The key change is adding a check to see if the clicked portfolio item is already active. If it is, we'll reset everything; if not, we'll activate it like before.

Update your JavaScript to this:

function clearSelection() {
  document.querySelector('.portfolio-container').classList.remove('portfolio-active-1', 'portfolio-active-2', 'portfolio-active-3', 'portfolio-active-4');
  document.querySelector('.portfolio-back-button').classList.remove('portfolio-back-button-visible');
}

function selectPortfolio(which) {
  const portfolioContainer = document.querySelector('.portfolio-container');
  // Check if the clicked item is already active
  const isCurrentlyActive = portfolioContainer.classList.contains(`portfolio-active-${which}`);
  
  // First clear any existing active state
  clearSelection();
  
  // Only activate the item if it wasn't already active
  if (!isCurrentlyActive) {
    portfolioContainer.classList.add(`portfolio-active-${which}`);
    document.querySelector('.portfolio-back-button').classList.add('portfolio-back-button-visible');
  }
}

2. Fix the Unclosed HTML Tag (Optional but Important)

I noticed your third portfolio picture's <a> tag isn't closed properly. Fix that to avoid unexpected behavior:

<div class="portfolio-picture portfolio-picture-3">
  <a href="#porfolio" onclick="selectPortfolio(3)">
    <img src="assets/img/portfolio/your-image-here.png" alt="Your Portfolio Item">
  </a>
</div>

How It Works

  • When you click a portfolio image that's not active: It clears any existing active content, then activates the clicked item's content (just like your original code).
  • When you click a portfolio image that is active: It clears the active state entirely, returning everything to the initial hidden/content-less view.
  • The back button still works as expected, since it calls clearSelection() directly.

Your existing CSS doesn't need any changes—all the transition and visibility logic stays intact.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:24:54