CSSJS-默认情况下,长li文本展开(溢出应隐藏)

CSS JS - Long li text is expanded by default (overflow should be hidden)

本文关键字:溢出 隐藏 文本 情况下 默认 li CSSJS-      更新时间:2023-09-26

我有几个li,其中包含一些文本。宽度是有限的,因此用户可以看到前30个字符。我试图实现两件事,在前30个字符后添加...(显然...应该在扩展模式下消失(,第二件事是能够扩展li以显示整个文本。现在,文本是默认展开的,不明白为什么。

小提琴在这里。

HTML:

<div>
  <ul>
    <li id="a">normal length text</li>
    <li id="b">this is a relatively long text</li>
    <li id="c">this is an example of a really long text</li>
    <li id="d">this is an example of an extremely long, pointless text. this is an example of an extremely long, pointless text</li>
  </ul>
</div>

CSS:

div {
  width: 250px;
}
div ul {
  text-align: left;
  padding: 0 10px;
}
ul li {
  list-style-position: inside;
  overflow: hidden;
  //text-overflow: elipsis;
}

JS:

$("li").on("click", function() {
  var titleLength = $(this).context.innerHTML.length;
  if (titleLength > 30) {
    if ($(this).height() == 18) {
    $(this).css('height', 'auto');
    var height = $(this).height();
      $(this).height(18).animate({height: height}, 200)
    } else {
      $(this).animate({
        height: 18
      }, 200)
    }
  }
});

默认情况下,您不会为li元素提供任何受限制的height,这意味着它们默认为auto,从而包含整个字符串。

当您的jQuery代码在关闭时将其高度设置为18px时,只需添加以下内容:

ul li {
  height: 18px;
  ...
}

修改的JSFiddle。


最重要的是:

  1. 您在text-overflow属性中拼写"省略号"不正确
  2. 将忽略text-overflow属性,而不指定添加值为nowrapwhite-space属性
  3. 完成此操作后,您需要在jQuery中删除并重新添加white-space属性

以下是另一个经过修改的JSFiddle演示,其中考虑了以上所有内容。

首先,设置为ellipsis,而不是elipsis,注意双l。此外,您没有约束li元素的大小,因此该设置不会产生任何效果。您需要在元素上设置width,并在默认情况下停止元素包装。

为了实现扩展逻辑,您可以在单击时切换一个类,从而取消使text-overflow工作所需的CSS规则。试试这个:

$("li").on("click", function() {
  $(this).toggleClass('expand');
});
div {
  width: 250px;
  background-color: lightgrey;
}
div ul {
  text-align: left;
  padding: 0 10px;
}
ul li {
  list-style-position: inside;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
ul li.expand {
  white-space: normal;
  overflow: visible;
  text-overflow: clip;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <ul>
    <li id="a">normal length text</li>
    <li id="b">this is a reletively long text</li>
    <li id="c">this is an example of a really long text</li>
    <li id="d">this is an example of an extremdsfsdfs sgdfdsfgdfg ertwerr wee www ely long, pointless text</li>
  </ul>
</div>

溢出li之后不需要javascript添加...

ul li {
  list-style-position: inside;
  overflow: hidden;
  text-overflow: elipsis;
  white-space: nowrap;
  text-overflow: ellipsis;
}

然后在单击li 时更改white-space属性

$("li").on("click", function() {
  $(this).css('white-space','normal');
});

自己试试https://jsfiddle.net/tcfLgom9/3/