【问题标题】:How to use blur event for <img> tag如何为 <img> 标签使用模糊事件
【发布时间】:2020-02-25 13:29:26
【问题描述】:

当我单击屏幕上除图像以外的任何位置时,我需要关闭div。 onblur 函数甚至没有调用 alert。请帮忙。

$('.myClass').on('blur', function() {
  alert("test");
  $('.divClass').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="myImg.png" height="23" width="18" class="myClass" style="margin-top: -42px!important;margin-left: 145px !important;position:relative;" onclick="test()" />

【问题讨论】:

  • 仅供参考,我认为图像没有blur 事件,blur 主要用于输入和文本字段。尝试用click 代替blur,图像上不需要onclick 属性
  • 您在 html 中定义 .myClass 的位置?
  • @RaeeshAlam 就在 img 标签中
  • 你可以通过按钮元素来实现,所以你需要在按钮内包裹IMG。

标签: javascript jquery html jquery-ui


【解决方案1】:

&lt;img&gt; 元素,默认情况下无法获得焦点。如果他们不能集中注意力,那么他们就不能失去焦点,从而触发blur 事件。虽然您可以使用 tabindex 来更改它,但您需要做很多其他工作(例如添加 ARIA)以使其可访问。最好只使用语义 HTML 开始。

  1. 用&lt;button type="button"&gt; 元素包裹&lt;img&gt;。
  2. 将事件处理程序从img 移动到button
  3. 应用 CSS 尽可能多地删除按钮的默认样式(如边框和背景颜色)。

【讨论】:

    【解决方案2】:

    默认img元素不能有焦点,因此通过代理不能触发blur事件。要解决此问题,您可以将tabindex 属性添加到img 以便可以选择它。然后它将触发blur 事件。

    请注意,这可能会干扰屏幕阅读器和其他辅助工具的行为,具体取决于页面的结构和内容,因此请谨慎使用此技术。

    $('.myClass').on('blur', function() {
      console.log("test");
      $('.divClass').hide();
    });
    .myClass {
      margin-top: -42px!important;
      margin-left: 145px !important;
      position: relative;
      outline: 0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img src="myImg.png" height="23" width="18" class="myClass" tabindex="1" />
    
    <div class="divClass">I will hide when the img loses focus...</div>

    【讨论】:

      【解决方案3】:

      您可以用button 元素包装img。然后你可以在按钮上触发blur & focus 事件,因为默认情况下img 没有blur 事件。

      $('.myClass').on('blur', function(){
        $('.divClass').hide();
      });
      .btn-forimg{
        padding: 0;
        margin: 0;
        border: none;
        box-shadow: none;
        outline: none;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      
      <button class="btn-forimg myClass"><img src="https://i.stack.imgur.com/fcbpv.jpg" width="50"></button>
      <div class="divClass">This div will disappear when button blur</div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多