使用jquery仅获取省略号文本 [英] Get only the ellipsis text using jquery

查看:112
本文介绍了使用jquery仅获取省略号文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的代码,只是想知道是否可以查询并获取省略号文本(即带有点而不是原始文本)?

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)?

如果我添加文本


这是一个长句

This is a long sentence

和(使用相关的省略号css)缩短为

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


这是一个长期的...

This is a long sen ...

有没有办法获取文本

"This is a long sen ..." 

来自 $( p) DOM对象而不是原始文本?

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

推荐答案

有一个草稿 需要一些特定于浏览器的调整

JavaScript:

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.

我怀疑字母间距或类似?

这篇关于使用jquery仅获取省略号文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆