最后,我找到了解决方案。由于我的原始解决方案已包含在问题中,因此我将将此答案编辑为新答案。
这是工作小提琴:https://jsfiddle.net/Kretiss/mbt68qw2/
首先,这里是 HTML。将editWidth 类添加到可能被编辑的段落中。
<div class="container">
<div class="column">
<div class="columnChild">
<img src="smile.jpg">
<p class="">Some text</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p>Some text that wraps because its long long long</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p>Some text</p>
</div>
</div>
<div class="column">
<div class="columnChild">
<img src="smile.jpg">
<p>Some longerrrrr text</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p>Some text</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p class="editWidth">Some text that wraps because its long sad Some text that wraps because its long</p>
</div>
</div>
</div>
CSS 几乎相同。
*{
box-sizing: border-box;
}
.container{
max-width: 500px;
width: 100%;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: flex-start;
border: 2px solid black;
}
.column{
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
border: 1px solid red;
}
.columnChild{
display: flex;
justify-content:flex-start;
align-items: center;
}
.columnChild img{
height: 50px;
}
这就是魔法。例如,通过此脚本将 JQuery 包含到文件中
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 然后添加这个脚本:
<script>
$(document).ready(function(){
$.fn.textWidth = function(){
const html_org = $(this).html();
const html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
const width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
function changeWidth(resizing){
const elements = $(".editWidth");
elements.each(function(index){
if(resizing) $(this).css("width", "auto");
const currentWidth = $(this).textWidth();
$(this).css("width", currentWidth + 2);
});
}
changeWidth(false);
$(window).resize(function(){
changeWidth(true);
});
});
</script>
加载 DOM 后,所有内容都以 changeWidth(false); 开头。它使用 false 参数调用 changeWidth(resizing) 函数,因为浏览器窗口没有调整大小。此函数循环遍历所有段落,其中包含editWidth 类。在.each() 函数内部调用$.fn.textWidth 函数,该函数返回段落内文本的精确宽度。之后,$(this).css("width", currentWidth + 2); 行将段落宽度设置为文本宽度 + 2px(您可以根据需要更改)。
当用户调整浏览器大小时,
$(window).resize(function(){
changeWidth(true);
});
被调用并执行与上述相同的操作。唯一的区别是它首先将段落的宽度设置为自动,否则文本的宽度可能与实际不同。
返回文本精确宽度的函数来自这篇文章:Calculating text width