【问题标题】:Unchecking checkbox does nothing [duplicate]取消选中复选框什么都不做[重复]
【发布时间】:2020-11-09 21:57:18
【问题描述】:

这是我的菜单栏
关闭:

已打开:

当窗口超过某个断点时,我希望菜单栏关闭。 这是代码:
html

<div class="d-md-none" id="menuButton">
                <input id="responsive-menu" type="checkbox" onchange="handleChange(this)">
                <label id="menuButtonMin" for="responsive-menu">
                <svg class="ham hamRotate ham4" viewBox="0 0 100 100" width="50" onclick="this.classList.toggle('active')">
                    <path class="line top" d="m 70,33 h -40 c 0,0 -8.5,-0.149796 -8.5,8.5 0,8.649796 8.5,8.5 8.5,8.5 h 20 v -20"></path>
                    <path class="line middle" d="m 70,50 h -40"></path>
                    <path class="line bottom" d="m 30,67 h 40 c 0,0 8.5,0.149796 8.5,-8.5 0,-8.649796 -8.5,-8.5 -8.5,-8.5 h -20 v 20"></path>
                </svg>
                </label>
            </div>

JS
window.addEventListener('resize', function(){
    const check = document.getElementById('responsive-menu');
    if(check.checked){
        if (window.innerWidth > 845){
            check.checked = false;
        }
    }
})

即使在控制台中,我看到 check 在断点后有一个 False 值,菜单仍然打开。有什么帮助吗?

【问题讨论】:

    标签: javascript html checkbox menu


    【解决方案1】:

    更改选中的值不会触发onchange 事件。你必须自己触发它。在check.checked = false;之后添加:

    if ("createEvent" in document) {
      var evt = document.createEvent("HTMLEvents");
      evt.initEvent("change", false, true);
      check.dispatchEvent(evt);
    }
    else
      element.fireEvent("onchange");
    

    【讨论】:

    • handleChange(check)
    • 嗯,这听起来很有趣......但我仍然得到一个错误:fireEvent is not a function
    • @AleksandreBregadze 没错,fireEvent 是老东西。我通过使用 dispatchEvent 纠正了它。这样,只有当您的浏览器不支持事件创建时,您才会使用 fireEvent(我猜是 IE9
    • 效果不错!
    • 但是,现在我有下一个问题,它不会改变标签的状态。调整大小后,按钮仍保持“X”形状。也许还有什么?
    猜你喜欢
    • 1970-01-01
    • 2014-04-27
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2018-02-03
    相关资源
    最近更新 更多