您可能遇到过 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 */
&[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: "";
}
}

仅此而已。希望你觉得它有用!
以上就是将占位符文本添加到 div 并使用 contenteditable="true"的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号