简体   繁体   English

在模糊/焦点事件上,如果下一个焦点位于同一个父元素中,如何才能使模糊不触发?

[英]On blur/focus events, how can you get blur not to fire if the next focus is in the same parent element?

I think the question is pretty straight forward.我认为这个问题很直接。 The code is below.代码如下。

<button onclick="toggleMenu()">Show Menu</button>

<div id="parent" class="hidden">
    <input type="text"></input>
    <input type="text"></input>
    <input type="text"></input>
</div>

<script>

    let parent = document.getElementById('parent');

    parent.addEventListener('focus', function () {
        // show parent
    });

    parent.addEventListener('blur', function () {
        // hide parent
    });

</script>

The idea is that parent is something like a hamburger menu.这个想法是parent就像一个汉堡包菜单。 It has an outside element where you can toggle the visible state of it.它有一个外部元素,您可以在其中切换它的可见状态。 For accessibility reasons, I'd like to understand how I can make it visible or showing based on the focus of the input fields.出于可访问性原因,我想了解如何根据输入字段的焦点使其visibleshowing

Is this at all possible?这是可能吗?

The code above works but I'm concerned about onblur() and onfocus() being called EVERY time the user changes input fields.上面的代码有效,但我担心onblur()用户更改输入字段时都会调用onblur()onfocus()

You can watch the mousedown or touchstart event on parent.您可以在 parent 上观看 mousedown 或 touchstart 事件。 If I remember it correctly, you can check if target element contained in parent, and if so, prevent event to stop next events, and because of that no blur would happen.如果我没记错的话,您可以检查父元素中是否包含目标元素,如果是,则阻止事件停止下一个事件,因此不会发生模糊。

The main disadvantage of that behavior is that the action triggered not on click event, and user can't just cancel it moving cursor away from the menu item holding the mouse button.该行为的主要缺点是操作不是在点击事件上触发的,用户不能只是取消它,将光标从按住鼠标按钮的菜单项移开。

Add some delay to the action you want to perform on the blur and constraint the action according to a flag which you set on the focus:为您要在模糊上执行的操作添加一些延迟,并根据您在焦点上设置的标志约束该操作:

let parent = document.getElementById('parent');
let focused = false;

parent.addEventListener('focus', function () {
    focused = true;
    console.log('show');
}, true);

parent.addEventListener('blur', function () {
    focused = false; // reset the flag
    setTimeout(function () {
        if (focused) return; // cancel if another input focused after the blur
        console.log('hide');
    }, 100);
}, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM