【问题标题】:Click link inside div that shows when input field is in focus单击显示输入字段何时处于焦点的 div 内的链接
【发布时间】:2019-04-20 02:55:34
【问题描述】:

如此简单的 CSS 在这里输入焦点时显示一个 div:

.ulclass {
  background: #f0a;
  display: none;
  height: 200px;
  width: 200px;
}
form:focus-within + ul.ulclass {
  display: block;
}
<form>
  <input type="text" value="Enter some text here" class="inputclass">
</form>
<ul class="ulclass">
  <a href="https://google.com">link</a>
</ul>

我在显示的 div 中有一个链接,但是我无法单击它,因为这样做会在触发链接之前模糊输入字段。有人对如何更好地做到这一点有任何建议吗?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    将带有:hover 伪类的ulclass 添加到focus 规则中:

    .ulclass {
      background: #f0a;
      display: none;
      height: 200px;
      width: 200px;
    }
    form:focus-within + ul.ulclass, ul.ulclass:hover {
      display: block;
    }
    <form>
      <input type="text" value="Enter some text here" class="inputclass">
    </form>
    <ul class="ulclass">
      <a href="https://google.com">link</a>
    </ul>

    【讨论】:

    【解决方案2】:

    您可以使用 JavaScript 而非 CSS 显示 div。另外,将 display:none; 指令分离到它自己的 CSS 类中,这样就可以在不删除其余样式的情况下删除它。

    这种方法是标准的,适用于所有客户端。

    document.querySelector("input.inputclass").addEventListener("focus", function(){
      document.querySelector(".ulclass").classList.remove("hidden");
    });
    .ulclass {
      background: #f0a;
      height: 200px;
      width: 200px;
    }
    
    .hidden {  display: none; }
    <form>
      <input type="text" value="Enter some text here" class="inputclass">
    </form>
    <ul class="ulclass hidden">
      <a href="https://google.com">link</a>
    </ul>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 2021-09-17
      相关资源
      最近更新 更多