javascript - 手机导航点击出jquery

标签 javascript jquery html css

我有一个功能,当用户单击移动导航之外时关闭移动菜单。我认为我的代码不正确,因为当我单击移动菜单时,它会立即打开和关闭。 我想要发生的是当用户单击导航幻灯片外部时将菜单切换回来。

当前代码是:

    // Responsive menu
$('.mobile-menu').click(function(e) {
    e.preventDefault();
    $('nav').slideToggle('slow');
});
// Close out the menu on click outside
window.addEventListener('mouseup', function(event) {
    var box = document.getElementById('nav');
    if(event.target != box && event.target.parentNode != box) {
        $('nav').slideToggle('slow');
    }
});

我认为这与 mouseup 有关,但我在可用参数中没有看到鼠标单击。

谢谢

最佳答案

我可以为您提供一种更简洁的方法。 仅应在菜单展开后绑定(bind)窗口的监听器。当它折叠时,应该删除监听器。这将防止由于 2 个事件监听器的异步执行而导致的许多麻烦和可能的错误。 考虑到这一点:

// First we define a callback function to be called after the nav complete showing, which will close the nav when a user tap outside.
var bindEventListener = function(event) {
    var box = document.getElementById('nav');
    if(event.target != box && event.target.parentNode != box) {
        $('nav').slideUp('slow', function(){
            // remove the window's event listener after the nav is closed
            window.removeEventListener('mouseup', bindEventListener);
        });
    }
});

// Now we set the button's onclick event and bind the above defined callback for mouseup event.
$('.mobile-menu').click(function(e) {
    e.preventDefault();
    $('nav').slideDown('slow', function(){
        window.addEventListener('mouseup', bindEventListener);
    });
});

关于javascript - 手机导航点击出jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778450/

相关文章:

javascript - 在overlayImage中应用滤镜的方法在哪里?

javascript - Rails - 使用 Javascript/HTML 上传文件

javascript - 将新的 Google Sheets 数据附加到 BigQuery 表中

javascript - 将 .on 事件与对象绑定(bind)

javascript - 通过javascript下载音频对象

javascript - HTML:iframe 沙箱替代品

php - Codeigniter ajax使用ajax代码将数据发送到 Controller

jquery - 使用 Ember.js 正确 Hook domready

javascript - CDN 失败时加载本地 JS/CSS 的 HTML if 语句

Javascript 触发 Tropo 脚本问题