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

求助:点击时改变section尺寸,解决focus失效与链接跳转异常

解决点击section放大后点击链接不缩小的问题

核心问题是focus状态会在点击内部链接时转移到<a>标签,导致section失焦恢复原尺寸。我们改用自定义CSS类+JavaScript控制状态的方案,让放大状态持久化,不随焦点转移或页面其他点击而消失。

修改后的完整代码

CSS 样式

section {
  background-color: rgb(153, 0, 0);
  color: white;
  text-decoration: none;
  border: none;
  border-radius: 50%;
  display: inline-flex;
  overflow: hidden;
  max-width: 200px;
  max-height: 200px;
  margin: 50px;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease; /* 平滑过渡动画 */
}

/* 用自定义类替代:focus,持久化放大状态 */
section.expanded {
  max-height: 100%;
  max-width: 100%;
  border-radius: 75px;
  background-color: #F7BBB1;
}

section.expanded .text {
  color: #000000;
  display: block; /* 放大后显示链接区域 */
}

section.expanded .title {
  color: #990000;
  font-size: 1.266rem;
  font-weight: 500;
  line-height: 1.15;
  padding: 20px; /* 调整标题内边距,适配放大后的布局 */
}

.text {
  color: #fff;
  text-align: left;
  font-size: 16px;
  padding: 20px;
  display: none; /* 默认隐藏链接 */
}

.title {
  color: #fff;
  text-align: center;
  font-size: 16px;
  padding: 75px;
}

.row {
  text-align: center;
}

HTML 结构

<div class='header'>
  <?php include ('header.php'); ?>
</div>
<main>
  <h2>Test Sections</h2>
  <p> Click </p>
  <br>
  <div class="row">
    <section id="expandable-section">
      <span class="title">
        Demo #1
      </span>
      <span class="text">
        <a href="https://example.com">Test</a>
      </span>
    </section>
  </div>
</main>
<footer>
  <?php include('footer.php'); ?>
</footer>

JavaScript 控制逻辑

const section = document.getElementById('expandable-section');

section.addEventListener('click', function(e) {
  // 点击链接时不切换状态,确保正常跳转
  if (e.target.tagName === 'A') return;
  this.classList.toggle('expanded');
});

关键改动说明

  1. 替换:focus为自定义类:expanded类是持久状态,不会因为焦点转移而消失,解决了点击链接后section缩小的问题。
  2. 链接区域默认隐藏:默认状态下隐藏.text,点击section放大后再显示,符合“点击后展示链接”的需求。
  3. 点击链接不触发状态切换:判断点击目标是否为链接,避免误操作导致section缩小,保证链接正常跳转。
  4. 平滑过渡动画:添加transition属性让尺寸变化更自然,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:17:52