Get only the ellipsis text using jquery

匆匆过客 提交于 2019-12-10 14:53:46

问题


Nice code, just wondered if it is possible to query and get the ellipsis text (i.e. with the dots in and not the original text)?

If I add the text

This is a long sentence

and (using the relevant css for ellipsis) it gets shortened to

This is a long sen ...

Is there a way to get the text

"This is a long sen ..." 

from the $("p") DOM object rather than the original text?


回答1:


I have a rough draft that needs some browser-specific tweaking.

JavaScript:

jQuery.fn.getShowingText = function () {
    // Add temporary element for measuring character widths
    $('body').append('<div id="Test" style="padding:0;border:0;height:auto;width:auto;position:absolute;display:none;"></div>');
    var longString = $(this).text();
    var eleWidth = $(this).innerWidth();
    var totalWidth = 0;
    var totalString = '';
    var finished = false;
    var ellipWidth = $('#Test').html('&hellip;').innerWidth();
    var offset = 7; // seems to differ based on browser (6 for Chrome and 7 for Firefox?)
    for (var i = 0;
    (i < longString.length) && ((totalWidth) < (eleWidth-offset)); i++) {
        $('#Test').text(longString.charAt(i));
        totalWidth += $('#Test').innerWidth();
        totalString += longString.charAt(i);
        if(i+1 === longString.length)
        {
            finished = true;
        }
    }
    $('body').remove('#Test'); // Clean up temporary element
    if(finished === false)
    {
        return totalString.substring(0,totalString.length-3)+"…";
    }
    else
    {
        return longString;
    }
}
console.log($('#ellDiv').getShowingText());

CSS:

#Test {
    padding:0;
    border:0;
    height: auto;
    width: auto;
    position:absolute;
    white-space: pre;
}
div {
    width: 100px;
    white-space: nowrap;
    border: 1px solid #000;
    overflow:hidden;
    text-overflow:ellipsis;
    padding:0;
}

With the caveat that the offset needs to change depending on the browser, unless someone can figure out what is causing it.

I suspect letter-spacing or similar?



来源:https://stackoverflow.com/questions/21095222/get-only-the-ellipsis-text-using-jquery

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