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

求助:实现文本框focus与blur状态切换的消息交互效果

Fixing Text Input Focus/Blur Message Toggle

Hey there! Let's sort out your focus/blur interaction issue. The main problem with your current code is that it targets two separate elements (#msg and #blur-msg)—so when you blur the input, the focus message stays visible instead of being removed like you want.

Here are two straightforward fixes depending on how you want to structure your message elements:

Option 1: Use a Single Message Container (Simplest Approach)

This method overwrites the message content in one container, so the focus message gets replaced automatically when the blur event triggers:

$(function() {
  $("#name").focus(function() {
    // Update the shared container with the focus message
    $("#message-box").html("<i>Ah, I see you like clicking boxes...</i>");
  });

  $("#name").blur(function(){
    // Replace the focus message with the blur message in the same container
    $("#message-box").html("<b>WHERE DO YOU THINK YOU'RE GOING?!</b>");
  });
});

Pair this with a single message container in your HTML:

<input type="text" id="name">
<div id="message-box"></div>

Option 2: Toggle Visibility of Separate Message Elements

If you prefer keeping two distinct elements for each message, we'll show/hide them instead of just setting their HTML content:

$(function() {
  $("#name").focus(function() {
    // Show the focus message and hide the blur message
    $("#msg").html("<i>Ah, I see you like clicking boxes...</i>").show();
    $("#blur-msg").hide();
  });

  $("#name").blur(function(){
    // Hide the focus message and show the blur message
    $("#msg").hide();
    $("#blur-msg").html("<b>WHERE DO YOU THINK YOU'RE GOING?!</b>").show();
  });
});

Make sure your HTML elements start hidden (so no messages show by default):

<input type="text" id="name">
<div id="msg" style="display: none;"></div>
<div id="blur-msg" style="display: none;"></div>

The core issue in your original code was that you never hid or replaced the focus message when the input lost focus. Either of these solutions will ensure only the correct message is visible at each state.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:54:46