勾选复选框时如何将Font Awesome图标从fa-info切换为fa-link
复选框勾选切换Font Awesome图标实现方案
需求说明
现有一组带Font Awesome info图标的复选框,基于Bootstrap框架开发,需要实现如下交互:
- 勾选复选框时,对应图标从
fa fa-info切换为fa fa-link - 取消勾选时,图标切回
fa fa-info
现有资源说明
已引入样式
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
单复选框HTML结构
<div class="col-12 col-sm-6 col-lg-4"> <input type="hidden" name="extraOption3Title" value="Sales" /> <label class="card d-flex flex-row p-2 mb-2 align-items-stretch openerp_enterprise_pricing_app " for="extraOption3"> <div class="openerp_enterprise_pricing_app_icon pr-2 flex-shrink-0 flex-grow-0" style="max-width: 50px"> <img class="img-fluid" src="pricing/icons/15.0/sale_management/static/description/icon.svg" alt="Sales" loading="lazy"/> </div> <div class="d-flex flex-column flex-grow-1 flex-shrink-0 w-50 justify-content-between openerp_enterprise_pricing_app_name"> <div class="openerp_enterprise_pricing_app_real_name text-truncate" id="extraOption3Title">Sales</div> <div class="usa small"> <b><span class="amount_to_localize"> 17.0 </span> <span class="openerp_enterprise_pricing_currency">USD</span></b> / month </div> <div class="uae small"> <b><span class="amount_to_localize"> 15.0 </span> <span class="openerp_enterprise_pricing_currency">USD</span></b> / month </div> <div class="egypt small"> <b><span class="amount_to_localize"> 12.0</span> <span class="openerp_enterprise_pricing_currency">USD</span></b> / month </div> </div> <div class="d-flex flex-column justify-content-between align-items-center"> <input type="checkbox" class="openerp_enterprise_pricing_app_checkbox d-none" name="extraOption3" id="extraOption3" data-app-name="sale_management" data-app-depends="account" value="extraOption3"/> <span class="fa fa-check text-center"></span> <i class="o_dependencies_icon fa fa-info small" data-toggle="tooltip" data-animation="false" data-delay="0" title="Requires: Invoicing"></i> </div> </label> </div>
已编写CSS
.fa-info:before { content: "\f129"; } .openerp_enterprise_pricing_app.selected .o_dependencies_icon:before { content: "\f0c1"; }
项目访问地址:http://homey-eg.online/
预期效果参考:https://www.odoo.com/pricing
可行实现方案
方案1:纯CSS实现(无额外依赖,优先推荐)
你现有的HTML结构里,复选框和目标图标属于同一父级下的兄弟元素,直接用CSS的:checked伪类加兄弟选择器即可实现,不需要修改HTML也不需要加JS:
/* 保留原有样式,新增如下规则 */ .openerp_enterprise_pricing_app_checkbox:checked ~ .o_dependencies_icon:before { content: "\f0c1" !important; }
该方案兼容性好,所有支持CSS3的浏览器都能正常运行,性能最优。
方案2:JS实现(适合需要同时触发其他业务逻辑的场景)
如果勾选复选框时还要执行其他操作(比如统计总价、联动依赖模块等),可以用jQuery实现(Bootstrap3默认依赖jQuery,无需额外引入):
// 确保DOM加载完成后执行 $(document).ready(function(){ $('.openerp_enterprise_pricing_app_checkbox').on('change', function(){ const $targetIcon = $(this).siblings('.o_dependencies_icon'); if($(this).prop('checked')){ $targetIcon.removeClass('fa-info').addClass('fa-link'); // 此处可添加选中后需要执行的其他业务逻辑 } else { $targetIcon.removeClass('fa-link').addClass('fa-info'); // 此处可添加取消选中后需要执行的其他业务逻辑 } }) })
内容的提问来源于stack exchange,提问作者John Adams
相关产品推荐
相关产品推荐

