【问题标题】:Reset input value button only visible on focused input not working重置输入值按钮仅在聚焦输入上可见不起作用
【发布时间】:2020-06-12 09:52:41
【问题描述】:

任务看起来很简单,所以我希望找到一个简单的解决方案,可能是纯 CSS。

我有一个输入字段。如果选中,将出现一个带有点击事件的按钮。为了简单起见,如果输入没有聚焦,我将使用 CSS 隐藏按钮。

但点击永远不会执行。好像CSS是在点击之前应用的,所以当onclick被触发时,按钮已经消失了。

关于如何解决这个问题的任何想法?

Array.from(document.getElementsByTagName("button")).forEach(function(button, index) {
  button.onclick = function() {
    document.getElementsByTagName("input")[index].value = "";
  };
});
.hide>input:not(:focus)+button {
  display: none;
}
<html>

  <body>
    <div>
      <input type="text" value="working">
      <button>Reset</button>
    </div>

    <div class="hide">
      <input type="text" value="not working">
      <button>Reset</button>
    </div>
  </body>

</html>

【问题讨论】:

  • 你正在使用 JS,所以试试这个,$(':text').focus(function(e){ $('.list_search').toggle(); }).blur(function(e){ $('.list_search').toggle(); });

标签: javascript html css focus


【解决方案1】:

Array.from(document.getElementsByTagName("button")).forEach(function(button, index) {
  button.onclick = function() {
    document.getElementsByTagName("input")[index].value = "";
  };
});
.hide>input:not(:focus)+button {
  display: none;
}
<html>

  <body>
    <div>
      <input type="text" value="working">
      <button>Reset</button>
    </div>

    <div class="hide">
      <input type="text" value="not working">
      <button onmousedown="return false">Reset</button>
    </div>
  </body>

</html>

我自己找到的,和我预想的一样简单:

<button onmousedown="return false">Reset</button>

成功了。

【讨论】:

  • 它实际上比我的解决方案更好,因为焦点停留在输入上。您甚至应该将其添加到另一个按钮。
【解决方案2】:

您的假设似乎是正确的。看起来确实像是在 javascript 之前应用了 CSS。

您可以通过在 css 属性上添加转换延迟来解决它。 不适用于display,所以我不得不改用visibility。如果您希望它的行为类似于display: none,可以添加position: absolute;

Array.from(document.getElementsByTagName("button")).forEach(function(button, index) {
  button.onclick = function() {
    document.getElementsByTagName("input")[index].value = "";
  };
});
button {
  transition: visibility 0.05s;
}

.hide>input:not(:focus)+button {
  visibility: hidden;
  /*position: absolute; Uncomment to obtain the same effect as display: none*/
}
<html>

<body>
  <div>
    <input type="text" value="working">
    <button>Reset</button>
  </div>

  <div class="hide">
    <input type="text" value="not working">
    <button>Reset</button>
  </div>
</body>

</html>

【讨论】:

    猜你喜欢
    • 2014-09-08
    • 2020-01-15
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多