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

在WordPress Contact Form 7中实现自定义样式切换开关

实现Contact Form 7双选项切换开关并提交值

1. 在Contact Form 7中构建切换开关的表单结构

在CF7的表单编辑框里,替换掉原有复选框/单选按钮代码,插入以下内容:

<div class="cf7-toggle-container">
  <input type="radio" id="looking-for-work" name="search-type" value="ik ben op zoek naar werk" checked>
  <label for="looking-for-work" class="toggle-option-work">werk</label>
  
  <input type="radio" id="looking-for-talent" name="search-type" value="ik ben op zoek naar talent">
  <label for="looking-for-talent" class="toggle-option-talent">talent</label>
  
  <span class="toggle-slider"></span>
</div>
  • name="search-type"是字段标识,两个单选按钮的name必须一致,才能实现单选互斥
  • value中的文本是最终会随邮件发送的完整选项内容
  • checked用于设置默认选中第一个选项

2. 添加自定义CSS实现切换样式

将以下CSS代码添加到WordPress主题的「自定义CSS」面板,或Contact Form 7的额外样式区域:

/* 隐藏原生单选按钮 */
.cf7-toggle-container input[type="radio"] {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* 切换容器整体样式 */
.cf7-toggle-container {
  position: relative;
  display: inline-block;
  width: 200px;
  height: 40px;
  background-color: #f0f0f0;
  border-radius: 20px;
  cursor: pointer;
  user-select: none;
}

/* 左右选项标签样式 */
.toggle-option-work, .toggle-option-talent {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
  width: 50%;
  text-align: center;
  font-size: 14px;
  color: #666;
  transition: color 0.3s ease;
}

.toggle-option-work {
  left: 0;
}

.toggle-option-talent {
  right: 0;
}

/* 滑动块样式 */
.toggle-slider {
  position: absolute;
  top: 2px;
  left: 2px;
  width: calc(50% - 4px);
  height: calc(100% - 4px);
  background-color: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  transition: left 0.3s ease;
}

/* 选中状态的文本和滑块位置变化 */
#looking-for-work:checked ~ .toggle-option-work {
  color: #007cba;
}

#looking-for-talent:checked ~ .toggle-option-talent {
  color: #007cba;
}

#looking-for-talent:checked ~ .toggle-slider {
  left: calc(50% + 2px);
}

可根据需求调整width、height或颜色值,匹配你想要的视觉样式。

3. 配置邮件发送字段

在CF7的「邮件」设置标签中,将[search-type]标签插入到邮件内容的合适位置,选中的选项文本就会和姓名等其他字段一同发送到指定邮箱。

4. 可选:强制验证(如需默认不选中)

若不想默认选中任何选项,去掉代码中的checked属性,同时给其中一个单选按钮添加required属性,例如:

<input type="radio" id="looking-for-work" name="search-type" value="ik ben op zoek naar werk" required>

这样用户必须选择一个选项才能提交表单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:12:41