search
HomeWeb Front-endJS Tutorialjs realizes that exceeding the text becomes an ellipsis

In actual projects, due to the uncertainty of the length of the text content and the fixity of the page layout, it is inevitable that the text content exceeds the p (or other tags, the same below) area. In this case, a better approach is When the text exceeds the limited p width, it is automatically displayed with an ellipsis (...). In this way, according to custom, people will know that there is text here that has been omitted. There is a property in css called text-overflow:ellipsis; for example, using css you can write like this:

{width:27em; white-space:nowrap; text-overflow:ellipsis; -o-text- overflow:ellipsis; overflow:hidden;} Only in the Firefox browser, the text overflow ellipsis representation cannot be realized. The text is clicked directly from the middle. I will not talk about how to use CSS to achieve this. The specific CSS implementation You can go to Baidu yourself. The most important thing for me here is to talk about how to use JS to implement it, and how to write a simple component through JS. I can directly call the initialization method of JS to implement it! For example, the following effect: The dots after

will prompt the user that there is more content that is not displayed to complete this effect!

Cut the nonsense first! First, let’s take a look at the demo effect I made, so that you can understand what the effect is!

If you want to see the effect, please click me! OK?

1: Let’s first look at the configuration items of the component: as follows:

targetCls

null, The required items of the container to be intercepted by the target default to null

limitLineNumber 1, The number of lines to be displayed defaults to 1 line

type '...', The type displayed exceeds the length of the container. The default is ellipsis

lineHeight 18, The line height of the dom node The default line height is 18

isShowTitle true, title Whether title is required to display all content, the default is true

isCharLimit false Based on the length of characters, limit the display of ellipses exceeding

maxLength 20 The default length is 20. After 20 characters, an ellipsis is displayed

2: Analysis

1. First, let’s talk about this component: it supports 2 ways to intercept strings. First: According to the character length to intercept, and an ellipsis will be displayed after exceeding it. For example, I call it like this:

new MultiEllipsis
({ "targetCls" :
 '.text8', 
 "isCharLimit":
 true, "maxLength": 18
  });

This initialization means that isCharLimit is true, which means that the number of characters is used to intercept. The maximum length maxLength is 18, so initialization , because the code will first determine if isCharLimit is true, and then intercept directly based on the number of characters, such as the following code:

2. The second type is intercepted based on the number of lines and height, such as The row height of the default configuration item is 18. If I want to display 2 rows, that means the height h = 18*2. If the height of the container is 100, then the interception method is:

Use (100 - The length of type - 1) Is it greater than 18×2? If it is greater, continue to intercept, otherwise it will not intercept and the ellipsis effect will be displayed! The following code:

Disadvantages: However, if you use row height interception, it is ok if the data is relatively small, but if there is a lot of data, such as a height of 500 pixels or more, it will relatively affect Performance, because they have to calculate n times each time (n means there are many functions called in a loop).

All the JS codes are as follows:

/*
 
* 基于JS的MultiEllipsis
 
* @author tugenhua
 
*/
 
function MultiEllipsis(options) {
 
  var self = this;
 
  self.options = $.extend({},defaults,options || {});
 
  self._init();
 
}
 
$.extend(MultiEllipsis.prototype,{
 
   // 页面初始化
 
  _init: function(){
 
    var self = this,
 
      cfg = self.options;
 
    if(cfg.targetCls == null || $(cfg.targetCls + "")[0] === undefined) {
 
      if(window.console) {
 
        console.log("targetCls不为空!");
 
      }
 
      return;
 
    }
 
    if(cfg.isShowTitle) {
 
      // 获取元素的文本 添加title属性
 
      var title = self.getText();
 
      $(cfg.targetCls ).attr({"title":title});
 
    }
 
    // 如果是按照字符来限制的话 那么就不按照高度来比较 直接返回
 
    if(cfg.isCharLimit) {
 
      self._charCompare();
 
      return;
 
    }
 
    self._compareHeight(cfg.lineHeight * cfg.limitLineNumber);
 
  },
 
  /*
 
   * 按照字符的长度来比较 来显示文本
 
   * @method _charCompare {private}
 
   * @return 返回新的字符串到容器里面
 
   */
 
  _charCompare: function(){
 
    var self = this,
 
      cfg = self.options;
 
    var text = self.getText();
 
    if(text.length > cfg.maxLength) {
 
      var curText = text.substring(0,cfg.maxLength);
 
      $($(cfg.targetCls + "")[0]).html(curText + cfg.type);
 
    }
 
  },
 
  /*
 
   * 获取目标元素的text
 
   * 如果有属性 data-text 有值的话 那么先获取这个值 否则的话 直接去html内容
 
   * @method getText {public}
 
   */
 
  getText: function(){
 
    var self = this,
 
      cfg = self.options;
 
    return $.trim($($(cfg.targetCls + "")[0]).html());
 
  },
 
  /*
 
   * 设置dom元素文本
 
   * @method setText {public}
 
   */
 
  setText: function(text){
 
    var self = this,
 
      cfg = self.options;
 
    $($(cfg.targetCls + "")[0]).html(text);
 
  },
 
  /*
 
   * 通过配置项的 行数 * 一行的行高 是否大于或者等于当前的高度
 
   * @method _compareHeight {private}
 
   */
 
  _compareHeight: function(maxLineHeight) {
 
    var self = this;
 
    var curHeight = self._getTargetHeight();
 
    if(curHeight > maxLineHeight) {
 
      self._deleteText(self.getText());
 
    }
 
  },
 
  /*
 
   * 截取文本
 
   * @method _deleteText {private}
 
   * @return 返回被截取的文本
 
   */
 
  _deleteText: function(text){
 
    var self = this,
 
      cfg = self.options,
 
      typeLen = cfg.type.length;
 
    var curText = text.substring(0,text.length - typeLen - 1);
 
    curText += cfg.type;
 
    // 设置元素的文本
 
    self.setText(curText);
 
    // 继续调用函数进行比较
 
    self._compareHeight(cfg.lineHeight * cfg.limitLineNumber);
 
  },
 
  /*
 
   * 返回当前dom的高度
 
   */
 
  _getTargetHeight: function(){
 
    var self = this,
 
      cfg = self.options;
 
    return $($(cfg.targetCls + "")[0]).height();
 
  }
 
});
 
var defaults = {
 
  'targetCls'        :   null,         // 目标要截取的容器
 
  'limitLineNumber'     :   1,           // 限制的行数 通过 行数 * 一行的行高 >= 容器的高度
 
  'type'          :   '...',         // 超过了长度 显示的type 默认为省略号
 
  'lineHeight'       :   18,         // dom节点的行高
 
  'isShowTitle'       :    true,        // title是否显示所有的内容 默认为true
 
  'isCharLimit'       :   false,        // 根据字符的长度来限制 超过显示省略号
 
  'maxLength'        :   20          // 默认为20
 
};

Related recommendations:

CSS limits the number of characters displayed beyond the limit and uses ellipsis to indicate

How to display the ellipsis '...' when the title text overflows

htmlHow to use ellipsis when the text control display exceeds the number of characters

The above is the detailed content of js realizes that exceeding the text becomes an ellipsis. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools