You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未填写第一个文本框时,点击第二个文本框如何阻止blur事件生效?

解决blur事件导致元素意外隐藏的问题

我完全懂你的困扰——明明只是想切换到第二个输入框,结果因为第一个框是空的,blur事件直接把提示div给藏起来了,折腾半天确实闹心。咱们可以通过检查焦点转移目标或者延迟判断的方式来搞定这个问题,下面给你具体的解决方案:

问题根源

当你点击第二个输入框(.a)时,第一个输入框(.b)的blur事件会先于.a的focus事件触发。因为.a在.d这个div里面,一旦.blur触发隐藏了.d,.a就会从页面上消失,导致它的focus事件根本没机会执行,最终div就一直处于隐藏状态。

解决方案一:利用event.relatedTarget判断焦点去向

我们可以在blur事件里,通过event.relatedTarget获取即将获得焦点的元素,判断这个元素是不是在.d内部。如果是,就不隐藏div:

<input type="text" class="b"><br>
<div class="d" style="display: none;">
 I want to disappear
 <input type="text" class="a">
</div>
$(document).ready(function() {
  $(".b").focus(function(){
    $(".d").show();
  });
  $(".a").focus(function(){
    $(".d").show();
  });
  
  $(".b").blur(function(event){
    // 检查失去焦点后,焦点是否转移到了.d内部的元素
    const isMovingToD = $(event.relatedTarget).closest('.d').length > 0;
    if(this.value.length > 0 || isMovingToD){
      $(".d").show();
    }else{
      $(".d").hide();
    }
  });
  
  $(".a").blur(function(){
    if(this.value.length > 0 || $(".b").val().length > 0){
      $(".d").show();
    }else{
      $(".d").hide();
    }
  });
});

解决方案二:延迟判断当前焦点元素

如果relatedTarget在某些场景下不可靠(比如浏览器兼容性问题),我们可以用setTimeout延迟一小段时间,等焦点完全转移后,再判断当前页面的活动元素是不是.a:

$(document).ready(function() {
  $(".b").focus(function(){
    $(".d").show();
  });
  $(".a").focus(function(){
    $(".d").show();
  });
  
  $(".b").blur(function(){
    const $this = $(this);
    setTimeout(() => {
      // 检查当前焦点是否在.a上,或者.b有内容
      if($this.val().length > 0 || document.activeElement.classList.contains('a')){
        $(".d").show();
      }else{
        $(".d").hide();
      }
    }, 100); // 100ms足够让焦点完成转移
  });
  
  $(".a").blur(function(){
    if(this.value.length > 0 || $(".b").val().length > 0){
      $(".d").show();
    }else{
      $(".d").hide();
    }
  });
});

额外优化:抽离重复逻辑

为了避免代码冗余,你可以把显示/隐藏div的逻辑抽成一个独立函数,让代码更简洁:

$(document).ready(function() {
  const toggleDVisibility = function() {
    const bHasValue = $(".b").val().length > 0;
    const aHasValue = $(".a").val().length > 0;
    const isFocusedOnA = document.activeElement.classList.contains('a');
    const isFocusedOnB = document.activeElement.classList.contains('b');
    
    if (bHasValue || aHasValue || isFocusedOnA || isFocusedOnB) {
      $(".d").show();
    } else {
      $(".d").hide();
    }
  };

  $(".b").focus(toggleDVisibility);
  $(".a").focus(toggleDVisibility);
  
  $(".b").blur(function(){
    setTimeout(toggleDVisibility, 50);
  });
  $(".a").blur(toggleDVisibility);
});

这样修改后,不管你是从空的.b切换到.a,还是在两个输入框之间来回切换,.d都不会意外消失啦。

内容的提问来源于stack exchange,提问作者Asterisk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:38:45