问题 CSS / JS只显示适合容器的整个单词


我发现那篇文章

https://justmarkup.com/log/2015/07/dealing-with-long-words-in-css/

我想知道如果它适合容器,如何强制显示整个单词:

例如

some long sentence

它可以显示为

some long s...

这个单词 sentence 不适合所以我想隐藏它并仅显示:

some long

我现在的CSS(它增加了 ...

.short {
    max-width: 250px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

7284
2018-06-18 10:42


起源

我们在谈论句子中单词的字符限制吗? - perkes456
也许你可以尝试使用overflow:hidden? - Linus Aronsson
JavaScript允许? - Bram Vanroy
@Bram Vanroy - 是的,JS是允许的 - Tony


答案:


你可以试试这个:

.element{
    display: block;
    width: 100px;
    overflow: hidden;
    word-wrap: break-word;
    text-overflow: ellipsis;
    max-height: 16px;
    line-height: 16px;
}
<div class="element">some long string</div>

哪里 max-height:= line-height:× <number-of-lines>


9
2018-06-18 11:05



据我所知,你实际上并不需要 text-overflow: ellipsis 为了这个效果(和唯一的影响 word-wrap: break-word 是确保即使文本的第一个单词不适合容器,它也不会在字符中间被切断)。 - Ilmari Karonen


只需让文字溢出

.short {
  max-width: 250px;
  height: 1em;
  overflow: hidden;
  position: relative;
}

0
2018-06-18 10:59





您可以将文本限制为一定数量的字符。然后,您必须找到空格字符的最后一个索引,并使用此索引再次限制文本。

这是一些示例代码:

function limitText(text, maxLength) {
    if (text.length <= maxLength) {
        return;
    }

    text = text.substr(0, maxLength);

    var lastSpace = text.lastIndexOf(' ');

    return text.substr(0, lastSpace) + '...';
}

limitText('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.', 20);

如果您只想限制单词数,可以使用此代码:

var maxWords = 4;
var text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
var newText = text.split(' ').slice(0, maxWords).join(' ');

0
2018-06-18 10:56



在那种情况下,我们应该得到字符串长度,而不仅仅是字符数 - Tony


尝试这个,

div{
white-space: nowrap;
width: 70px;
overflow: hidden;
}
div > p{
white-space: nowrap;
width: 70px;
overflow: hidden;
}

<div><p>some long sentences</p></div>
<div>some long sentences</div>

0
2018-06-18 10:57



看起来它不起作用 jsbin.com/wunadoyewo/edit?html,css,output - Tony
@Tony提供的jsbin链接在我的浏览器中工作得很好,即chrome。 - frnt
我在使用FIrefox - Tony
现在在firefox中检查一下,尝试在div或para标签中增加和减小宽度。 - frnt
它补充说 ... 无论如何 - Tony