Is it possible to add placeholder in div tag

前端 未结 4 1101
南方客
南方客 2020-12-04 12:26

I would like to display some text to the user when my div element is empty.

I have tried adding a placeholder attribute to my div but the t

相关标签:
4条回答
  • 2020-12-04 12:31

    Assuming what you really want to do is to have the user input some text and show him some placeholder in the input field, this is what you can use:

    <input type="text" value="Enter the text" onfocus="if(this.value=='Enter the text'){this.value='';}" onblur="if(this.value==''){this.value='Enter the text';}" />
    

    Of course you can wrap the input in a div.

    <div><input [...] /></div>
    

    You can see this in action here

    0 讨论(0)
  • 2020-12-04 12:43

    i have already answered to such a question here with this test : http://codepen.io/gcyrillus/pen/hzLIE

    div:empty:before {
      content:attr(data-placeholder);
      color:gray
    }
    

    see If editable div have no text than set placeholder

    0 讨论(0)
  • 2020-12-04 12:51

    This can also be achieved without the use of the contentEditable attribute, using plain CSS.

    Using the :empty pseudo-class along with the ::before pseudo-element you can add a placeholder to an empty element.

    The following example provides a fallback placeholder for div elements that do not have a data-placeholder attribute defined.

    Example:

    div:empty::before {
      color: grey;
    }
    div[data-placeholder]:not([data-placeholder=""]):empty::before {
      content: attr(data-placeholder);
    }
    div:empty::before {
      content: 'fallback placeholder';
    }
    <div data-placeholder='data- placeholder'></div>
    <br>
    <div></div>

    0 讨论(0)
  • 2020-12-04 12:53

    There are lot of options using javascript, but if you want to do it in css.Try this:

    html:

    <div contentEditable=true data-text="Enter text here"></div>
    

    css:

    [contentEditable=true]:empty:not(:focus):before{
        content:attr(data-text)
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题