【问题标题】:How to make a button appear only when input is focused如何使按钮仅在输入聚焦时出现
【发布时间】:2020-01-15 18:03:21
【问题描述】:

这是我的 HTML:

<template>
  <div>
    <div v-if="id!==undefined">
      <strong>ID</strong>
      <input
        id="id"
        v-model="id"
        type="text"
        readonly
      >
        <button
          type="button"
          @click="doCopy"
        >
          <font-awesome-icon :icon="copyIcon" />
        </button>
    </div>
  </div>
</template>

这是我的 CSS:

<style scoped>
  input {
    margin-left: 2px;
    border: none;
  }
  input:focus {
    border: 1px solid #21abd4;
    border-radius: 5px;
    button: visible;
  }
  button {
    visibility: hidden;
    border: none;
    background: none;
  }

</style>

我想要只在输入集中时才显示按钮的东西,尝试了多种方法,例如尝试从内部调用按钮。 input:focus 但 IDE 抱怨这一点。尝试配对 input:focus + button 但这也不起作用,所以不知道如何将两者链接在一起:(

任何指针都会很棒。

【问题讨论】:

    标签: html css vue.js


    【解决方案1】:

    您可以使用 CSS adjacent sibling selector (+) 来完成此操作:

       input:focus + button
    

    选择紧跟在input:focus 元素之后的button

    input {
      margin-left: 2px;
      border: none;
    }
    
    input:focus {
      border: 1px solid #21abd4;
      border-radius: 5px;
    }
    
    input:focus + button {
      visibility: visible;
    }
    
    button {
      visibility: hidden;
      border: none;
      background: none;
    }
    <div>
      <div >
        <strong>ID</strong>
        <input id="id" type="text" readonly />
        <button type="button" @click="doCopy">
          Copy 
        </button>
      </div>
    </div>

    也就是说,Vue 中还有一些方法可以更新共享状态,并根据输入的状态设置按钮的可见性。

    【讨论】:

      【解决方案2】:

      这可以通过 jQuery 轻松完成:

      $("input").focus(function() {
        $("button").css("visibility", "visible");
      });
      
      $("input").focusout(function() {
        $("button").css("visibility", "hidden");
      });
      button {
          visibility: hidden;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <input type="text"/><button>Submit</button>

      【讨论】:

      • 这会放在 vue 文件中的什么位置?
      • @Will 我从来没有用过 Vue,对不起。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      相关资源
      最近更新 更多