Home Web Front-end JS Tutorial js realizes that exceeding the text becomes an ellipsis

js realizes that exceeding the text becomes an ellipsis

Mar 02, 2018 pm 03:32 PM
javascript become

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
  });
Copy after login

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
 
};
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles