Home  >  Article  >  Web Front-end  >  js realizes that exceeding the text becomes an ellipsis

js realizes that exceeding the text becomes an ellipsis

小云云
小云云Original
2018-03-02 15:32:062567browse

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