jQuery expander with max-lines property

跟風遠走 提交于 2020-01-03 04:48:05

问题


I really thinks jQuery Expander plugin is great but it can't do satisfy my needs. It cuts text and put a "read more" button after the text which expands the text. But it only cuts when the text length is more than a specified value. But what if the text is:

Some text:




Blah blah

The text use as much space as a text with many characters but the Expander will not cut it off. I want to have a max lines property so I can restrict both on text length and max lines. Any plugin suggestions?


回答1:


I have constructed this jQuery which is partly taken from fudgey's link. Unfortunately, it uses px instead of em because I need to compare height of the div with .height(). It could also be prettier to make it to a function but it works :)

$(document).ready(function () {
    var maxlines = 12;
    var lineheight = 15; // line height in 'px'
    var maxheight = (maxlines * lineheight);
    var allowedExtraLines = 3;
    var showText = "Læs mere...";
    var hideText = "Skjul tekst...";

    $('.Truncate').each(function () {
        var text = $(this);
        if (text.height() > maxheight + allowedExtraLines * lineheight) {
            text.css({ 'overflow': 'hidden', 'line-height': lineheight + 'px', 'height': maxheight + 'px' });

            var link = $('<a href="#">' + showText + '</a>');
            link.click(function (event) {
                event.preventDefault();

                if (text.css('height') == 'auto') {
                    $(this).html(showText);
                    text.css('height', maxheight + 'px');
                } else {
                    //$(this).remove();
                    $(this).html(hideText);
                    text.css('height', 'auto');
                }
            });

            var linkDiv = $('<div></div>');
            linkDiv.append(link);

            $(this).after(linkDiv);
        }
    });
});


来源:https://stackoverflow.com/questions/1779764/jquery-expander-with-max-lines-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!