将 HTML 文本的结尾替换为几个点



>我有以下标记:

<h5>
  <a href="javascript:void(0);">I am a very long title and I need to be shortened</a>
</h5>

我怎样才能做到,如果h5文本超过一定数量的字符,我去掉其他字符并用"..."替换它们?

这应该有效。您必须将内联元素显示为块。

编辑:刚刚意识到如果H5超过字符数,则要添加点,而不是超过宽度。我认为要做到这一点,您将需要使用 JS - 查看另一个答案。

h5 {
  display: block;
  white-space: nowrap;
  width: 12em;
  overflow: hidden;
  text-overflow: ellipsis;
  color: red; /* This needs to match the color of the anchor tag */
}
a:link {
  color: red;
}
<h5>
  <a href="javascript:void(0);">I am a very long title and I need to be shortened</a>
</h5>

你可以这样做:

var name = $('a').text();
if (name.length > 20) {
    var shortname = name.substring(0, 20) + " ...";
    $('a').replaceWith(shortname);
}
如果你想

使用javascript,你可以通过原型来扩展String对象:

String.prototype.limit = function(length) {
    return this.length > length ? (this.substring(0, length) + '...') : this;
}
var str = 'qwertyuiop';
console.log(str.limit(5)); // qwert...
<h5 id="expansion">
  <a id="myLink" href="javascript:void(0);">I am a very long title and I need to be shortened And Also I am a very long title and I need to be shortened</a>
</h5>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
if($('#myLink').text().length > 20){
    var linkText = $('#myLink').text();
    $('#myLink').html(linkText.substring(0,20)+"...")
    $('#myLink').on("click",function(){
        console.log("linkText :: ",linkText);
        $('#myLink').html(linkText);
    });
}
</script>

这个正在工作

        <h5>
          <a class ="one" href="javascript:void(0);">I am a very long title and I need to be shortened</a>
        </h5>
        <style>
    .one
    {
      white-space: nowrap;
      overflow:hidden;
      text-overflow: ellipsis;
      display:inline-block;
      width : 100px;
    }
</style>

根据您的网站设计设置宽度

最新更新