JS控制文字只显示两行,超出部分显示省略号

时间:2024-03-09 09:30:22

 

由于使用css控制文字只显示多行,超出部分显示省略号,存在一定的兼容性问题,所以总结了一下网上一些大咖使用js实现控制行数的解决方案。

第一步:依次引入jquery.js+jquery.ellipsis.js+jquery.ellipsis.unobtrusive.js。

(1)jquery.js源代码下载  http://jquery.com/

(2)jquery.ellipsis.js   源代码

可以通过该部分修改默认的行数,修改row的值即可。

(function($) {
    $.fn.ellipsis = function(options) {

        // default option
        var defaults = {
            \'row\' :2, // show rows
            \'onlyFullWords\': false, // set to true to avoid cutting the text in the middle of a word
            \'char\' : \'...\', // ellipsis
            \'callback\': function() {},
            \'position\': \'tail\' // middle, tail
        };

        options = $.extend(defaults, options);

        this.each(function() {
            // get element text
            var $this = $(this);
            var text = $this.text();
            var origText = text;
            var origLength = origText.length;
            var origHeight = $this.height();

            // get height
            $this.text(\'a\');
            var lineHeight =  parseFloat($this.css("lineHeight"), 10);
            var rowHeight = $this.height();
            var gapHeight = lineHeight > rowHeight ? (lineHeight - rowHeight) : 0;
            var targetHeight = gapHeight * (options.row - 1) + rowHeight * options.row;

            if (origHeight <= targetHeight) {
                $this.text(text);
                options.callback.call(this);
                return;
            }

            var start = 1, length = 0;
            var end = text.length;

            if(options.position === \'tail\') {
                while (start < end) { // Binary search for max length
                    length = Math.ceil((start + end) / 2);

                    $this.text(text.slice(0, length) + options[\'char\']);

                    if ($this.height() <= targetHeight) {
                        start = length;
                    } else {
                        end = length - 1;
                    }
                }

                text = text.slice(0, start);

                if (options.onlyFullWords) {
                    text = text.replace(/[\u00AD\w\uac00-\ud7af]+$/, \'\'); // remove fragment of the last word together with possible soft-hyphen characters
                }
                text += options[\'char\'];

            }else if(options.position === \'middle\') {

                var sliceLength = 0;
                while (start < end) { // Binary search for max length
                    length = Math.ceil((start + end) / 2);
                    sliceLength = Math.max(origLength - length, 0);

                    $this.text(
                        origText.slice(0, Math.floor((origLength - sliceLength) / 2)) +
                               options[\'char\'] +
                               origText.slice(Math.floor((origLength + sliceLength) / 2), origLength)
                    );

                    if ($this.height() <= targetHeight) {
                        start = length;
                    } else {
                        end = length - 1;
                    }
                }

                sliceLength = Math.max(origLength - start, 0);
                var head = origText.slice(0, Math.floor((origLength - sliceLength) / 2));
                var tail = origText.slice(Math.floor((origLength + sliceLength) / 2), origLength);

                if (options.onlyFullWords) {
                    // remove fragment of the last or first word together with possible soft-hyphen characters
                    head = head.replace(/[\u00AD\w\uac00-\ud7af]+$/, \'\');
                }

                text = head + options[\'char\'] + tail;
            }

            $this.text(text);

            options.callback.call(this);
        });

        return this;
    };
}) (jQuery);
View Code

(3)jquery.ellipsis.unobtrusive.js源代码

(function ($) {
    var $ellipsis = $.fn.ellipsis;

    $ellipsis.unobtrusive = {

        parseElement: function (element) {
            var $element = $(element);
            var maxWidth = $element.data(\'ellipsis-max-width\');
            maxWidth = maxWidth ? parseInt(maxWidth) : 0;
            var maxLine = $element.data(\'ellipsis-max-line\');
            maxLine = maxLine ? parseInt(maxLine) : 1;
            $element.ellipsis({ maxWidth: maxWidth, maxLine: maxLine });
        },

        parse: function (selector) {
            $(selector).find("[data-ellipsis=true]").each(function () {
                $ellipsis.unobtrusive.parseElement(this);
            });
        }
    };


    $(function () {
        var beginAt = new Date;
        if($ellipsis.debug){
            console.log(beginAt);
        }

        $ellipsis.unobtrusive.parse(document);

        if($ellipsis.debug){
            var endAt = new Date;
            console.log(endAt);
            console.log(endAt - beginAt);
        }
    });
}(jQuery));
View Code

 

第二步:需要一个装载内容的容器,并在其上添加属性data-toggle="popover",data-ellipsis="true",data-toggle的值可以定义成其他的值,只需后续与调用的js保持一致即可,例如、

 <div style="width:400px">
      <p class="aptitude-title"  data-toggle="popover" data-ellipsis="true">JS控制文字只显示两行,超出部分显示省略号。</p>
</div> 

 建议添加一个外层容器,同时添加一个固定宽度。

第三步:调用方法

   $(function () {
            $("[data-toggle=\'popover\']").popover();
        });

 代码搬运,记录过程,便于后续的工作和学习。