简体   繁体   English

jQuery 触发点击焦点,但如果点击聚焦则不会

[英]jQuery trigger click on focus, but not if clicked to focus

I am working on an MDL site.我在MDL站点上工作。 There is known issue that they still don't give a default select form element.有一个已知问题,他们仍然没有提供默认的select表单元素。 The solution I found was to use a menu component , which will show when the input is clicked.我找到的解决方案是使用菜单组件,它会在单击input时显示。 Works well.效果很好。 But I noticed that the menu will not show up when the input is focused using the TAB key.但是我注意到当使用 TAB 键聚焦输入时菜单不会显示。 So I put this in jQuery:所以我把它放在 jQuery 中:

/*
Make menus show up on input focus
*/
$('.mdl-textfield__input').focus(function(){
    $(this).click();
});

This works well for showing the menu on TAB driven focus.这适用于在 TAB 驱动的焦点上显示菜单。 But the problem is that now when I click on the input, it will show and then hide the menu.但问题是现在当我点击输入时,它会显示然后隐藏菜单。 The real click shows it and the next simulated click from my code will cause it to close.真正的点击会显示它,我的代码中的下一次模拟点击将导致它关闭。

I am wondering if I can tell if the focus state was driven by a click or not, and condition my jQuery code on that.我想知道是否可以判断焦点状态是否由单击驱动,并以此为条件我的 jQuery 代码。 So if the focus was driven from a click then I don't need to simulate the click?因此,如果焦点是由点击驱动的,那么我不需要模拟点击?

Here is an example of the MDL HTML code:以下是 MDL HTML 代码的示例:

<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label {% if form.errors.gender %}is-invalid{% endif %}">
    <label class="mdl-textfield__label" for="gender">Gender</label>
    <input class="mdl-textfield__input" id="id_gender" name="gender" type="text" readonly value="{{ form.gender.value }}" readonly>
    <ul class="mdl-menu mdl-menu--bottom-left mdl-js-menu mdl-js-ripple-effect select-menu" for="id_gender">
        <li class="mdl-menu__item" data-val="m">Male</li>
        <li class="mdl-menu__item" data-val="f">Female</li>
        <li class="mdl-menu__item" data-val="t">Transgender</li>
        <li class="mdl-menu__item" data-val="o">Other</li>
    </ul>
    <span class="mdl-textfield__error">{{ form.errors.gender.as_text }}</span>
</div>
$('body').on('focus', '.mdl-textfield__input', function(e){
    $(this).trigger('click')
});

I had the exact same issue with a Drupal Superfish mobile menu and found the answer here Detect if focus event was triggered by user/browser or jQuery我在 Drupal Superfish 移动菜单上遇到了完全相同的问题,并在此处找到了答案检测焦点事件是否由用户/浏览器或 jQuery 触发

That answer specifically works for clicks, but you can rework for either.该答案特别适用于点击次数,但您可以针对其中任何一个进行返工。 Should be something like this:应该是这样的:

var isUserClick = false;
$('.mdl-textfield__input').mousedown(function(){
   isUserClick = true;
});
$('.mdl-textfield__input').focus(function(e){
  if (isUserClick === false){
    $(this).click();
  } else {
    isUserClick = false;
  }
});

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

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