如何基于条件通过input type button切换两种不同图标
解决按钮切换值与对应图标的方案
你的问题核心是要根据按钮的value状态动态切换图标,之前的CSS伪元素内容固定,无法随按钮状态变化,下面是可行的修改方案:
修改后的完整代码
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="btn-icon icon-yes"><input type="button" id="yes" value="Yes"/></span>
CSS
input[type="button"] { margin: 10px; padding-right: 30px; } span.btn-icon { position: relative; } /* Yes状态对应的图标 */ span.icon-yes::after { font-family: 'Material Design Icons'; content: "\F0138"; /* 替换为你需要的Yes图标编码 */ font-size: 13px; position: absolute; right: 20px; top: 1px; pointer-events: none; } /* No状态对应的图标 */ span.icon-no::after { font-family: 'Material Design Icons'; content: "\F0139"; /* 替换为你需要的No图标编码 */ font-size: 13px; position: absolute; right: 20px; top: 1px; pointer-events: none; }
JavaScript
$('#yes').click(function(e) { const $btn = $(this); const $parentSpan = $btn.parent(); if ($btn.val() === 'Yes') { $btn.val('No'); $parentSpan.removeClass('icon-yes').addClass('icon-no'); } else { $btn.val('Yes'); $parentSpan.removeClass('icon-no').addClass('icon-yes'); } });
关键改动说明
- 给包裹按钮的span添加了基础类
btn-icon和初始状态类icon-yes,用来区分不同状态下的图标样式 - 为Yes/No两种状态分别编写CSS伪元素样式,通过类名切换来加载不同的图标编码
- JS中切换按钮value的同时,同步修改父元素span的类名,实现图标的动态切换
你只需要把CSS中content属性的图标编码替换成你实际需要的Yes/No对应图标即可。
内容的提问来源于stack exchange,提问作者Justice
相关产品推荐
相关产品推荐

