jQuery实现指示灯颜色选择功能,禁用兄弟节点onclick事件

jQuery实现指示灯颜色选择功能,禁用兄弟节点onclick事件

功能需求

  • 有多种颜色的指示灯,保证只能亮起一种颜色的灯。
  • 当选中一种颜色的灯时,该灯亮起,其它的灯熄灭且不可操作,向后台传送选中的颜色(本篇不讨论数据传递)

HTML标签

<div class="lightchoose">
    <a class="light red off" style="cursor:not-allowed" href="javascript:void(0);" onclick="lightchoose('red')"></a>
    <a class="light green off" style="cursor:not-allowed" href="javascript:void(0);" onclick="lightchoose('green')"></a>
    <a class="light blue active" href="javascript:void(0);" onclick="lightchoose('blue')"></a>
    <a class="light yellow off" style="cursor:not-allowed" href="javascript:void(0);" onclick="lightchoose('yellow')"></a>
    <a class="light purple off" style="cursor:not-allowed" href="javascript:void(0);" onclick="lightchoose('purple')"></a>
    <a class="light cyan off" style="cursor:not-allowed" href="javascript:void(0);" onclick="lightchoose('cyan')"></a>
</div>
  • 在class中添加active则该灯处于亮起状态。
  • style=“cursor:not-allowed” 显示禁用样式。

坑点

  • style=“cursor:not-allowed” 这个style虽然能在页面上显示禁用的指示,但是并不能禁用JS的点击事件
  • 显示为禁止点击的图标,但是点击后灯还是会亮起,原因是CSS样式并不能禁用事件。

解决办法

  • 在class中添加 off 关键词,当JS函数检测到此关键词时,return
  • JS代码如下
function lightchoose(color) {
        var dom = '.' + color;
        if ($(dom).hasClass('off')) {
            return
        }
        $(dom).toggleClass('active');
        if ($(dom).hasClass('active')) {
            $(dom).siblings().attr('style', 'cursor:not-allowed');
            $(dom).siblings().addClass('off');
        } else {
            $(dom).siblings().removeAttr('style', 'cursor:not-allowed');
            $(dom).siblings().removeClass('off')
        }
    }

总结

  • CSS样式并不能禁用JS的事件。
  • 禁用兄弟节点的事件需要添加关键词标记,或者添加事件状态变量。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安心写bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值