Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - Non-JQuery cross-browser solution to add a multiline placeholder to a textarea input

This question is inspired by Insert line break inside placeholder attribute of a textarea?

I didn't find the accepted answer complete-- in part because I don't use JQuery, and in part because if the user enters a string that is exactly equal to the placeholder, the input will be deleted upon refocusing. Also, 
 is not supported by Safari in placeholders.

Any cross-browser non-JQuery solutions to creating a multiline placeholder for a textarea?

question from:https://stackoverflow.com/questions/65838213/non-jquery-cross-browser-solution-to-add-a-multiline-placeholder-to-a-textarea-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answering my own question -- complete with a dataset attribute to check if the 'value' of the textarea was entered by the user or is from the placeholder.

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;
        }
    });
}

Fiddle: https://jsfiddle.net/fm4vyxjL/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...