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

如何实现点击Read more按钮时切换背景及展开/收起文本

实现Read More/Less按钮背景切换的方案

核心思路

通过CSS类切换管理按钮不同状态的样式(推荐这种方式,符合样式与逻辑分离的最佳实践),或直接用JavaScript修改元素style属性。以下是具体实现方案:


方法1:CSS类切换(推荐)

把样式逻辑完全放在CSS中,JS仅负责切换状态类,代码更易维护。

HTML结构

<button class="read-more-btn">Read more</button>
<div class="expandable-text" style="display: none;">
  这里是点击后展开的文本内容...
</div>

CSS样式

/* 按钮默认样式 */
.read-more-btn {
  background-color: #e0e0e0; /* 初始背景色 */
  border: none;
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.3s ease; /* 平滑过渡效果 */
}

/* 展开状态下的按钮样式 */
.read-more-btn.active {
  background-color: #2196F3; /* 展开时的背景色 */
  color: white;
}

.expandable-text {
  margin-top: 10px;
  line-height: 1.5;
}

JavaScript逻辑

const readMoreBtn = document.querySelector('.read-more-btn');
const expandableText = document.querySelector('.expandable-text');

readMoreBtn.addEventListener('click', () => {
  const isExpanded = expandableText.style.display !== 'none';
  
  if (isExpanded) {
    // 收起文本:恢复按钮样式与文本
    expandableText.style.display = 'none';
    readMoreBtn.textContent = 'Read more';
    readMoreBtn.classList.remove('active');
  } else {
    // 展开文本:切换按钮样式与文本
    expandableText.style.display = 'block';
    readMoreBtn.textContent = 'Read less';
    readMoreBtn.classList.add('active');
  }
});

方法2:直接修改style属性

如果不想额外添加CSS类,也可以直接通过JS修改按钮背景色:

JavaScript调整版

const readMoreBtn = document.querySelector('.read-more-btn');
const expandableText = document.querySelector('.expandable-text');
const defaultBg = '#e0e0e0';
const expandedBg = '#2196F3';

readMoreBtn.addEventListener('click', () => {
  const isExpanded = expandableText.style.display !== 'none';
  
  if (isExpanded) {
    expandableText.style.display = 'none';
    readMoreBtn.textContent = 'Read more';
    readMoreBtn.style.backgroundColor = defaultBg;
    readMoreBtn.style.color = 'inherit';
  } else {
    expandableText.style.display = 'block';
    readMoreBtn.textContent = 'Read less';
    readMoreBtn.style.backgroundColor = expandedBg;
    readMoreBtn.style.color = 'white';
  }
});

关键说明

  • 用CSS类切换的方式更利于后续样式扩展,比如添加hover状态、边框变化等,直接在.read-more-btn.active中修改即可,无需改动JS。
  • 加入transition属性能让背景色变化更平滑,提升用户体验。
  • 若文本内容较多,也可通过max-height配合过渡实现平滑展开/收起的动画效果,替代直接切换display属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:05:25