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

如何用Toggle Switch切换价格文本?求jQuery实现方案

用jQuery实现切换开关切换月付/年付价格的方案

嘿,作为jQuery新手,这个需求其实非常直观,我来给你一步步拆解实现方法,保证你能轻松上手~

第一步:搭建基础HTML结构

首先我们需要一个定价表格,每个套餐里包含月付价格和年付价格,再加上一个切换开关。这里用原生的<input type="checkbox">做开关核心,配合<label>来美化样式:

<!-- 切换开关 -->
<div class="toggle-container">
  <label class="toggle-switch">
    <input type="checkbox" id="priceToggle">
    <span class="slider"></span>
  </label>
  <span>切换到月付</span>
</div>

<!-- 定价表格 -->
<table class="pricing-table">
  <thead>
    <tr>
      <th>基础套餐</th>
      <th>进阶套餐</th>
      <th>旗舰套餐</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <!-- 月付价格,初始隐藏 -->
      <td class="monthly-price" style="display: none;">¥39/月</td>
      <td class="monthly-price" style="display: none;">¥79/月</td>
      <td class="monthly-price" style="display: none;">¥129/月</td>
      <!-- 年付价格,初始显示 -->
      <td class="yearly-price">¥390/年(省2个月费用)</td>
      <td class="yearly-price">¥790/年(省2个月费用)</td>
      <td class="yearly-price">¥1290/年(省2个月费用)</td>
    </tr>
  </tbody>
</table>

第二步:美化切换开关的CSS

原生checkbox不好看,我们用CSS把它改成常见的滑动开关样式:

.toggle-container {
  margin: 20px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

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

/* 隐藏原生checkbox */
.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:checked + .slider:before {
  transform: translateX(26px);
}

第三步:编写jQuery切换逻辑

这部分是核心,我们监听开关的change事件,根据开关状态切换价格的显示/隐藏:

// 确保DOM加载完成后执行
$(document).ready(function() {
  // 监听开关变化
  $('#priceToggle').on('change', function() {
    if ($(this).is(':checked')) {
      // 开关开启:显示月付,隐藏年付
      $('.monthly-price').show();
      $('.yearly-price').hide();
      // 顺便更新旁边的提示文字
      $(this).closest('.toggle-container').find('span').text('切换到年付');
    } else {
      // 开关关闭:显示年付,隐藏月付
      $('.yearly-price').show();
      $('.monthly-price').hide();
      $(this).closest('.toggle-container').find('span').text('切换到月付');
    }
  });
});

额外小技巧:添加平滑过渡

如果想让价格切换更丝滑,可以给价格元素加上CSS过渡效果:

.monthly-price, .yearly-price {
  transition: all 0.3s ease;
}

这样切换时就会有自然的淡入淡出效果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:45:19