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

需求:为定价模块添加月/年付切换开关实现价格文本变更

实现月付/年付价格切换开关

1. 调整HTML结构

先给定价模块添加切换开关,同时为Essentials套餐的价格元素设置data-monthly和data-yearly属性,方便后续JS读取切换值:

<!-- 切换开关容器 -->
<div class="pricing-toggle">
  <label class="toggle-switch">
    <input type="checkbox" id="pricing-switch">
    <span class="slider"></span>
  </label>
  <span class="toggle-label">Monthly</span>
  <span class="toggle-label">Yearly</span>
</div>

<!-- 定价套餐模块(适配你的原有结构) -->
<div class="pricing-plan">
  <h3>Essentials</h3>
  <p class="plan-price" data-monthly="$9" data-yearly="$6">$9</p>
  <!-- 套餐其他内容 -->
</div>

2. 添加开关样式(CSS)

给开关做基础美化,可根据网页主题调整颜色和尺寸:

.pricing-toggle {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
  justify-content: center;
}

.toggle-switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.toggle-label {
  font-weight: 500;
}

3. 编写切换逻辑(JavaScript)

监听开关状态变化,动态更新价格文本:

// 获取开关和价格元素
const pricingSwitch = document.getElementById('pricing-switch');
const essentialsPrice = document.querySelector('.plan-price');

// 绑定切换事件
pricingSwitch.addEventListener('change', function() {
  essentialsPrice.textContent = this.checked 
    ? essentialsPrice.dataset.yearly 
    : essentialsPrice.dataset.monthly;
});

拓展说明

如果页面有多个套餐需要同步切换,只需给每个套餐价格元素都加上data-monthly和data-yearly属性,再用循环遍历更新:

pricingSwitch.addEventListener('change', function() {
  const allPrices = document.querySelectorAll('.plan-price');
  allPrices.forEach(priceEl => {
    priceEl.textContent = this.checked 
      ? priceEl.dataset.yearly 
      : priceEl.dataset.monthly;
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:56:04