使文字在内容中不可见

 收藏

I have a contenteditable span (display set to inline-block, so it doesn't act like a span, per se). I want the span to act like a password field on a linux terminal; you're typing, but you can't actually see it.

I've tried visibility: hidden and display: none, but both break the formatting and the text is still visible. Setting the color to the same as the background (black) makes the text invisible, but the caret is too.

我希望使用CSS完成此操作,但是如果无法完成,我将仅使用JavaScript。这是我的代码:

.input {
    display: inline;
}

body {
    background-color: black;
}

#field-in {
    color: #ffffff;
    outline: none;
    display: inline-block;
}
<div class="input">
    <span id="field"><span id="field-name">Invisible Text:</span><span id="field-in" contenteditable>&nbsp;</span></span>
</div>
回复
  • 雅蠛蝶 回复

    您可以更改插入标记的颜色,以便显示插入标记:

    .input {
        display: inline;
    }
    body {
        background-color: black;
        color: white;
    }
    #field-in {
        color: #000000;
        caret-color: #ffffff;
        outline: none;
        display: inline-block;
    }
    #field-in::selection, #field-in::-moz-selection {
        color: #000000;
        background-color: #000000;
    }
    <div class="input">
        <span id="field"><span id="field-name">Invisible Text:</span><span id="field-in" contenteditable>&nbsp;</span></span>
    </div>

  • Pete 回复

    两个CSS属性:

    1. color: rgba(0,0,0,0);
    2. caret-color: red;

    一个CSS伪元素:

    1. ::-moz-selection { background: rgba(0, 0, 0, 0); }
      ::selection { background: rgba(0, 0, 0, 0); }

    The caret needs a contrasting color so adjust accordingly with caret-color. The value rgba(0,0,0,0) is transparent black -- the fourth 0 is alpha (opacity). The selection highlight is the same color so if the user selects the text with the default color (blue in Chrome) the text would be not be revealed. Note, this will work with any color background.

    .input {
      display: inline-block;
    }
    
    body {
      background-color: none;
    }
    
    #field-in {
      outline: none;
      color: rgba(0, 0, 0, 0);
      caret-color: red;
      display: inline-block;
    }
    
    #field-in::-moz-selection {
      background: rgba(0, 0, 0, 0);
    }
    
    #field-in::selection {
      background: rgba(0, 0, 0, 0);
    }
    <div class="input">
      <span id="field"><span id="field-name">Invisible Text:</span><span id="field-in" contenteditable>Test</span></span>
    </div>