HTML - Keep placeholder when user types

前端 未结 5 646
清酒与你
清酒与你 2020-12-10 13:36

I have an input like this:


When I type something in the input the placeholder t

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 14:02

    This could be done by using the 'onchange' handler. You would write a fancy function that would concat the remainder of the placeholder onto what the user has typed, and would also place the cursor at the end of the user's text.

    Here's some untested, incomplete js/psuedocode to give you an idea:

    userTextLength: 0, // measure of how many chars the user has typed; need this because the length itself won't be a valid measure, since we're modifying it in place. Note that we're using the DOM as a source of truth here... alternative method would be to store the user's text itself here, but let's run with this.
    placeholder: "xx/yy/zz",
    onchange: function() {
      boxText = document.querySelector('#elem').value;
      if (boxText.length === 1) { // special handling for the first character they type. (Using placeholder text at first.)
        this.userTextLength++;
        placeholder = boxText.slice(userTextLength);
        userText = boxText.slice(0, userTextLength);
        document.querySelector('#elem').innerHTML = userText + placeholder;
      }
      if (boxText.length < placeholder.length) { // this would mean they used backspace, which also needs to be handled.
    
      }
      else { // the normal case, should look quite similar to the first if block
        this.userTextLength += 1;
        userInput = 
      }
    }
    

    Something I haven't handled here is the cursor focusing. That will need an 'onfocus' event, and will use the userTextLength property as well to decide where to place it. For some help on doing that, this answer looks like it should be helpful.

提交回复
热议问题