如何删除Jquery中元素溢出的文本 [英] How to remove text that is overflown from element in Jquery

查看:33
本文介绍了如何删除Jquery中元素溢出的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在开发一个Web应用程序,这是我的布局.div使用

So I am working on a web app, and this is my layout. The divs use

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

这在视觉上很好,在JSFiddle中也很好.但是,能够做出非常长的名字的能力在Web应用程序中存在问题.此问题来自以下事实:从技术上讲,它不是删除溢出的文本.它(您可能会想到隐藏"一词)将其隐藏.您将如何检测".Name"中的溢出文本?元素并将其删除?我想保持相同的外观和规则.只是隐藏的文本被删除.

This visually is fine, and is also fine in a JSFiddle. But with the ability to make very long names has issues in the web app. This issue comes from the fact that it isn't technically removing the overflown text. It (as you would think with the word "hidden") hides it. How would you go about detecting overflown text in the ".Name" element and removing it? I would like to keep the same look and rules. Just the text that is hidden is removed.

LINK- https://jsfiddle.net/t29ffzan/12/

推荐答案

问题在于,并非所有字母都占用相同的空间.例如I和M,其中M(猜测)约为I的3倍.

The issue is that not all letters take up the same amount of space as each other. For instance I and M where M (guessing) is ~ 3x as big as I. See this explanation.

但是,您可以猜测并接近,但是仍然不能保证.

However, you can guess and get close but there's still no guarantee.

$('.Name').each(function() {

  let text = $(this).text();
  let width = $(this).parent('.Box').outerWidth();
  let fontSize = 18 - ( 18 * 0.35 ); // Hardcoded from CSS
  let count = width/fontSize;
  text = text.substr(0, count);  
  $(this).text(text);

});

小提琴是上述示例,并且使用 font-size并删除CSS的〜35%,以允许使用更多字符,但是根据实际字母的使用,结果可能相差很大.

This fiddle is a working example of the above and uses the font-size in the CSS and removes ~ 35% to allow for more characters but depending on the actual letters uses the results may vary widely.

可以使用固定宽度字体,因为所有字符都应占用相同的空间.但是,结果仍然不是完美的.

You could use a fixed width font as all the characters should take up the same amount of space. However, results still aren't going to be perfect.

最好的选择是在创建名称时限制字符数,而不必回过头来尝试在事实成立后对其进行解析.

Your best bet is the limit the character count when the name is created instead of having to go back and try and parse it after the fact.

这篇关于如何删除Jquery中元素溢出的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆