【问题标题】:How to set the input area height equal to the placeholder paragraph's height如何设置输入区域高度等于占位符段落的高度
【发布时间】:2022-01-08 16:38:43
【问题描述】:

因为占位符包含的文字太多,为了显示出来,我在占位符上使用white-space:pre-line,所以占位符文字变成多行段落,但输入高度没有变化。

::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  white-space:pre-line;  
}
::-moz-placeholder { /* Firefox 19+ */
     white-space:pre-line;
}
:-ms-input-placeholder { /* IE 10+ */
    white-space:pre-line; 
}
:-moz-placeholder { /* Firefox 18- */
     white-space:pre-line;
}
input {
    width:300px;
    height:30px; /* I hope the height is not a static value, but can auto equal to the placeholder paragraph's height*/
}
<input type="text" placeholder="There are too many text, in order to show them, I set it to white-space:pre-line so it become multiple line paragraph"/>

在输入上设置静态高度不是一个好主意,因为如果用户缩放以调整浏览器大小,占位符文本大小也会发生变化,占位符变为动态的两行或三行。

有没有办法将输入区域的高度设置为占位符段落的高度?

【问题讨论】:

  • 我想不出用输入来做到这一点的方法,但你能切换到使用 contenteditable div 吗?在stackoverflow.com/questions/20726174/… 有一些关于在这样的元素中处理占位符的有趣想法

标签: html css


【解决方案1】:

你可以这样做

希望对你有帮助

HTML

<div id="test"></div>
<input placeholder="There are too many text, in order to show them, I set it to white-space:pre-line so it become multiple line paragraph">
<input placeholder="Please enter name, address">

CSS

::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  white-space:pre-line;  
}
::-moz-input-placeholder { /* Firefox 19+ */
     white-space:pre-line;
}
:-ms-input-placeholder { /* IE 10+ */
    white-space:pre-line; 
}
:-moz-placeholder { /* Firefox 18- */
     white-space:pre-line;
}

input::placeholder {
    width:100%;
    position:absolute;
    top:10px;
}
var input = document.querySelectorAll('input');
for(i=0; i<input.length; i++){
    let div = document.createElement("div");
    div.style.width = input[i].clientWidth + "px";
    div.style.display = "inline-block";
    div.innerHTML = input[i].getAttribute('placeholder');
    
    console.log(div);
    document.getElementById("test").append(div);
    let height = div.offsetHeight;
    input[i].setAttribute('style', 'height:' + (height + 10) + 'px');
    
}
document.getElementById("test").parentNode.removeChild(document.getElementById("test"));

【讨论】:

    猜你喜欢
    • 2021-08-10
    • 2020-06-11
    • 2014-12-31
    • 2021-10-08
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2017-05-11
    • 2017-02-25
    相关资源
    最近更新 更多