首页 > 解决方案 > 当输入框以 HTML 为焦点时如何做某事

问题描述

我有一个 ID 为“searchbox”的搜索框——我试图根据用户是否关注搜索框来显示和隐藏一个名为“feed”的元素。

<script>
document.getElementById("searchbox").addEventListener("focus", myFunction);

function myFunction() {
  document.getElementById("feed").style.display= "none";
}
</script>

上面的函数运行不正常(提要没有消失) - 所以如果我能得到一些关于如何更好地构造函数的指导,那就太好了

标签: javascripthtml

解决方案


feed要切换blur,除了focus.

这是一个工作示例。确保你的script标签在你的 DOM 元素之后:

<html>
  <input id="searchbox" type="input" />
  <div id="feed">feed</div>
  <script>
    const searchbox = document.getElementById("searchbox");
    const feed = document.getElementById("feed");
    searchbox.addEventListener("focus", () => feed.style.display = "none");
    searchbox.addEventListener("blur", () => feed.style.display = "block");
  </script>
</html>

推荐阅读