How to set an input width to match the placeholder text width

前端 未结 4 1292
梦毁少年i
梦毁少年i 2020-12-08 18:39

Example http://dabblet.com/gist/5859946

If you have a long placeholder, the input by default does not display wide enough to show all the placeholder text.

e

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 19:04

    A workaround i thought of:

    • Make a span element with the same text as placeholder.
    • Measure width of the span element.
    • Set input to the width of the span element.
    • hide span element. display none will not work, use other method.

    http://jsfiddle.net/Timar/cwLp3rbo/

    var input = document.getElementById('input-1');
    
    // measure width of same text as placeholder
    var placeholder =  document.getElementById('input-1-placeholder');
    
    
    input.style.width = placeholder.offsetWidth + "px"
    

提交回复
热议问题