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

菜单按钮勾选标记点击后无法保留,求前端解决方案

解决菜单按钮勾选标记点击后消失的问题

问题

点击菜单按钮时勾选标记会显示,但松开点击后立即消失,需求是勾选标记可持久显示,再次点击可取消。

解决方案

1. 修复HTML结构错误

原HTML存在多余的闭合标签,修正后:

<button class="menu">
    <div class="description">
        <h4>Fricassée d'escargots</h4>
        <p>Au piment d'Espelette</p>
    </div>
    <div class="menu_price">
        <div class="menu_check"></div>
    </div>
</button>

2. 添加JavaScript实现状态切换

通过切换active类来控制持久状态:

document.querySelectorAll('.menu').forEach(btn => {
  btn.addEventListener('click', () => btn.classList.toggle('active'));
});

3. 修改SCSS样式,替换:active为状态类

将原有的:active伪类替换为.active类,确保状态持久,同时优化动画:

.menu {
    background-color: $color_3;
    width: 634px;
    height: 72px;
    border-radius: 15px;
    overflow: hidden;
    cursor: pointer;
    
    .description {
        margin-top: -13px;
        margin-left: 20px;
        width: 572px;
        height: 42px;
    }

    .menu_price {
        display: flex;
        padding-left: 94%;
    }

    .menu_check {
        display: flex;
        width: 59px;
        height: 73px;
        margin-left: auto;
        margin-right: -65px;
        margin-top: -50px;
        background-color: $anim-color;
        justify-content: center;
        align-items: center;
        border-radius: 0 0 15px 0;
        position: relative;
        cursor: pointer;
        transition: margin-right 1s;
    }

    .menu_check::after {
        content: "";
        font-family: "FontAwesome";
        padding: .3125rem;
        border-radius: 50%;
        color: #99e2d0;
        font-size: .9375rem;
        background-color: #fff;
        transition: transform .4s ease-in-out;
    }

    // 使用.active类替代:active,实现持久选中状态
    &.active .menu_check {
        margin-right: 0;
        animation: slide 1s forwards; // forwards让动画结束后保持最终状态
    }

    @keyframes slide {
        0% {
            margin-right: -65px;
        }
        100% {
            margin-right: 0;
            transform: rotate(360deg); // 补全角度单位
        }
    }
}

核心要点

  • :active仅在鼠标按住时生效,改用自定义类.active配合JS切换实现持久状态
  • 动画添加forwards属性,确保动画结束后保留最后一帧样式
  • 修复原动画中rotate(360)缺少deg单位的语法问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:08:34