PHP前端开发

将占位符文本添加到 div 并使用 contenteditable=\"true\"

百变鹏仔 4周前 (09-19) #CSS
文章标签 符文

您可能遇到过 contenteditable 属性。它被用在很多地方。它是文本区域之类的更好的替代品。您可以将 contenteditable="true" 添加到任何 div,然后它就像一个输入字段。在本文中,我将向您展示如何向文本添加占位符,因为它不支持开箱即用的占位符属性。

需要的代码

div[contenteditable] {  &[placeholder]:empty::before {    content: attr(placeholder);    z-index: 9;    line-height: 1.7;    color: #555;    word-break: break-all;    user-select: none;  }  &[placeholder]:empty:focus::before {    content: "";  }}

这就是您需要的全部代码!但是,如果您只将其添加到 css 中,那么它将不起作用。您需要在 html 中添加占位符属性,并确保 div 可见。

完整代码/示例

html

<div contenteditable="true" placeholder="subscribe to axorax on yt! :d"></div>

css

div[contenteditable] {  /* Basic styles */  width: 20rem;  height: 15rem;  padding: 1rem;  background: #292929;  color: #fff;  /* Placeholder code */  &amp;[placeholder]:empty::before {    content: attr(placeholder);    z-index: 9;    line-height: 1.7;    color: #555;    word-break: break-all;    user-select: none;  }  &amp;[placeholder]:empty:focus::before {    content: "";  }}

仅此而已。希望你觉得它有用!