如果我在页面加载时知道三个文本字符串(但不是在设计时),例如:
如何在一些HTML元素(div或span很好)中放置文本而没有包装,例如当用户执行一些调整HTML元素大小的操作时,最长的文本是首选,但如果文本会溢出,切换到下一个不溢出的最短文本?调整小于最小文本的大小将隐藏任何溢出(即HTML元素将具有溢出:隐藏)。
答案 0 :(得分:1)
只要你愿意约束身高,你就可以用CSS做到这一点。由于您只需要1行文本,因此将高度限制为1em
似乎不合理。
浮动元素时,如果第一行没有足够的空间,它将流向下一行。此解决方案中的每一行都有两个项目:
1px
的断路器元件。不幸的是,根据我的测试,这个元素必须有一些宽度才能参与流程。文本必须排列得最短到最长,并且不得有透明背景。使用透明背景可以显示较短的文本。
.container {
white-space: nowrap;
height: 1em; /* Must be fixed height */
width: 100%; /* Or any width you want */
overflow: hidden; /* Make sure that the elements that are bumped down don't show */
border: 1px solid red; /* For example only */
}
.container p {
position: relative; /* Relative to allow shifting elements up */
float: left;
left: 0;
padding: 0;
margin: 0;
height: 1em; /* Text block must be fixed height */
background-color: white; /* Text block must be opaque */
}
.container .break {
float: left;
clear: left;
width: 1px;
height: 1em; /* Must be the same height as a text block */
}
/* Shift each longer text block up to sit atop the first one */
.container p:nth-child(4) {
top: -1em;
}
.container p:nth-child(6) {
top: -2em;
}
/* Code below is just to animate the width for the sake of this example, and is not part of the solution */
@keyframes changewidth {
from { width: 100%; }
to { width: 1%; }
}
.container {
animation-duration: 5s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}

<div class="container">
<div class="break"></div>
<p>Short summary</p>
<div class="break"></div>
<p>This is a shorter version of the summary text.</p>
<div class="break"></div>
<p>This is a really long version of the summary text. I could go on forever. Isn't this great?</p>
</div>
&#13;
答案 1 :(得分:0)
你不能用CSS做到这一点。使用JavaScript并遍历所有版本。留下适合的那个。您可以测量div高度以确定文本是否适合。
编辑(已添加示例):
HTML
<div class="ft" data-sh="{{ short-text }} data-tn=" {{ tiny-text }}">{{ long-text }}</div>
的jQuery
function fits(ele) {
var cur_height = ele.height();
ele.css('white-space', 'nowrap');
var obl_height = ele.height();
return cur_height == obl_height;
}
$(function(){
$('.ft').each(function() {
if( ! fits($(this)) {
$(this).html($(this).data('sh');
if( ! fits($(this)) {
$(this).html($(this).data('tn');
}
}
})
});
这可以写得更好,但我希望这会给你一个想法。未经测试。
答案 2 :(得分:0)
您没有提供任何HTML代码,但这是一个使用jQuery的工作版本,用于此类HTML结构。
<强> HTML 强>:
<div class="mydiv">
<p class="large">I am a paragraph</p>
<p class="med">I am a paragraph</p>
<p class="small">I am a paragraph</p>
</div>
<强> CSS 强>:
.mydiv {
width: 50px;
height: 50px;
border: 1px solid black;
}
.med {
font-size: .8em;
}
.small {
font-size: .2em;
}
.mydiv p {
display: none;
}
p.large {
display: block;
}
<强>的jQuery 强>:
$('.mydiv').children('p').each(function(i, el) {
if (this.scrollWidth > $(el).innerWidth()) {
$(el).css('display', 'none');
$(el).next('p').css('display', 'block');
}
});