gpt4 book ai didi

css - react : how to make an input only as wide as the amount of text provided?

转载 作者:行者123 更新时间:2023-12-04 02:31:13 24 4
gpt4 key购买 nike

很简单的问题:
我正在尝试创建与提供给它们的文本一样大的输入。
沙盒:https://codesandbox.io/s/long-snowflake-6u13n?file=/src/Test.jsx
我的设计意图是动态生成输入,然后允许用户具有特定于每个输入的样式,这些样式在视觉上有助于根据外部事件分解每个句子。但在我继续前进之前,我的输入容器 非常重要。仅 和里面的文字一样大。

why not use a textarea? -- I have data that is particular to each sentence that I want to create unique styles for.


有什么想法吗?

最佳答案

这是一种来自普通 HTML/CSS 和工作片段的方法,将输入的值隐藏在 span 中背后input设置在 absolute position . CSS可以使spaninput匹配相同的长度/宽度。拉伸(stretch)/折叠父级 (label) 将完成这项工作。
感谢@silvenon 您还可以在代码段下方找到一个 react 示例

var val = document.querySelector('#test');
let tpl = document.querySelector('#tpl');
let text = val.value;
tpl.textContent= text;

val.addEventListener("input", function () {// onchange ...
let text= val.value;
//console.log(text);
tpl.textContent= text;
});
label {
display: inline-block;
position: relative;
min-width: 2em;
min-height: 1.4em;
}

#tpl {
white-space: pre;
/* max-width : could be wised to set a maximum width and overflow:hidden; */
}

#test {
font-family: inherit;
font-size: inherit;
position: absolute;
vertical-align: top;
top: 0;
left: 0;
width: 100%;
background: white;
}
<label><span id="tpl"></span><input id='test' value="Some test to try" ></label>

在@silvenon 的帮助下,您可能会找到该代码的 react 示例。
const SentenceInput = styled.input`
padding: 0;
margin: 0;
border: none;
border: 1px solid black;
/* added styles */
font-family: inherit;
font-size: inherit;
position: absolute;
vertical-align: top;
top: 0;
left: 0;
width: 100%;
background: white;
`

const Label = styled.label`
display: inline-block;
position: relative;
min-width: 2em;
min-height: 1.4em;
`

const Template = styled.span`
white-space: pre;
/* max-width : could be wised to set a maximum width and overflow:hidden; */
`

const Sentence = ({ initialValue }) => {
const [value, setValue] = React.useState(initialValue)
return (
<Label>
<Template>{value}</Template>
<SentenceInput
type="text"
value={value}
onChange={(event) => {
setValue(event.target.value)
}}
/>
</Label>
)
}

关于css - react : how to make an input only as wide as the amount of text provided?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64092841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com