【问题标题】:Non-JQuery cross-browser solution to add a multiline placeholder to a textarea input将多行占位符添加到 textarea 输入的非 JQuery 跨浏览器解决方案
【发布时间】:2021-04-26 12:14:54
【问题描述】:
【问题讨论】:
标签:
javascript
textarea
placeholder
multiline
【解决方案1】:
回答我自己的问题 - 使用数据集属性来检查文本区域的“值”是由用户输入还是来自占位符。
function addMultilinePlaceholder(textarea, placeholder) {
// Does textarea have input entered by the user?
textarea.dataset.hasValue = '';
textarea.value = placeholder;
textarea.addEventListener('focus', function () {
if (!textarea.dataset.hasValue) {
this.value = '';
}
});
textarea.addEventListener('keyup', function () {
textarea.dataset.hasValue = (textarea.value.length > 0) ? 'true' : '';
});
textarea.addEventListener('blur', function () {
if (!textarea.dataset.hasValue) {
this.value = placeholder;
}
});
}
小提琴:https://jsfiddle.net/fm4vyxjL/1/