checkbox 实现单选效果(html)

本文提供了一个简单的HTML代码示例,演示如何利用checkbox标签实现类似单选按钮的功能,适合对圆点radio按钮有特殊需求的场景。代码包含jQuery的使用,通过事件监听实现了点击checkbox时的逻辑判断,确保每次只选中一个选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

note:在html <input> 标签类中的checkbox实现单选效果。

在最近的开发项目中,客户要求使用小方格子实现“单选”功能,显然圆点的radio被out了,只能选择chckbox的方块样式,也在网上搜过,可能有点儿脑残,没有找到。

废话不多说直接上代码:

ps:只是一个简单的demo。

 

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
    <title>checkbox实现单选效果</title>  
    <script src="jquery-1.7.2.min.js"></script>  
    <script>  
        $(document).ready(function () {  
            $('.sb').click(function () {  
                var typeThis = typeof ($(this).attr("checked"));  
                switch (typeThis) {  
                    case "string":  
                        if ($(this).attr("checked").toLowerCase()=="checked") {  
                            $('.sb').each(function () {  
                                $(this).removeAttr("checked");  
                            });  
                            $(this).attr("checked",true);  
                        }  
                        break;  
                    case "undefined":  
                        $('.sb').each(function () {  
                            $(this).removeAttr("checked");  
                        });  
                        break;  
                }  
            });  
        });  
    </script>  
</head>  
<body>  
    <input class="sb" type="checkbox" value="1"/>  
    <input class="sb" type="checkbox" value="2" />  
    <input class="sb" type="checkbox" value="3" />  
    <input class="sb" type="checkbox" value="4" />  
</body>  
</html>  

 

当然在case “undefined” 中的代码可有可无,大家可以试试

 

 

转载于:https://www.cnblogs.com/Ruonan-Li/p/3805881.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值