我有一个包含一些文本的元素,并且希望以最中心的字符应位于元素中间的方式将文本居中放置在元素内。例如。给定字符串“iiiii|MMMMM”“|”是最中心的字符,但在非等宽字体中 - 如果正常居中 - 更靠左。 “|”无论其他字符的字符宽度如何,都应位于元素的中心。
该元素也是一个输入,所以我不能将字符串拆分成它的字符。
希望您有一些想法,在此先感谢您。
最佳答案
不剪切字符串就无法对齐字符。
var arr = [];
var text1 = document.querySelector('#text1');
var text2 = document.querySelector('#text2');
document.querySelector('#textInput').addEventListener("input", function(){
arr = textInput.value.split('|')
text1.innerText = arr[0] || ''
text2.innerText = arr[1] || ''
})
.text-wrap{
width: 400px;
box-shadow: 0 0 3px orange;
font-size: 0;
}
.text-wrap span {
display: inline-block;
font-size: 1rem;
}
.text-wrap span:nth-child(1n){
width: calc(50% - 3px);
}
.text-wrap span:nth-child(2){
width: 6px;
text-align: center;
}
.text-wrap span:nth-child(1){
text-align: right;
text-indent: -99999px;
}
<div class="text-wrap">
<span id="text1">aaaadddddddddddddddddddddddddddddddddddddddddddddddddddddd</span>
<span>|</span>
<span id="text2">bb</span>
</div>
<input type="text" id="textInput"/>
关于html - 围绕字符串的中间字符居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573638/