使用jquery仅获取省略号文本

时间:2014-01-13 15:37:18

标签: javascript jquery ellipsis

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

如果我添加文字

  

这是一个长句

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

  

这是一个长期的......

有没有办法获取文字

"This is a long sen ..." 

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

2 个答案:

答案 0 :(得分:2)

尝试:

function getEllipsis(command, characters) {
	for (var i = command.length; i >= 0; i--) {
		if (command.substring(0, i).length < characters) {
			if (i < command.length) {
				command = command.substring(0, i) + "...";
			}
			return command;
		}
	}
}
console.log(getEllipsis("I am a long sentence",16))
console.log(getEllipsis("But I am even longer",20))

答案 1 :(得分:0)

have a rough draft 需要一些特定于浏览器的调整

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;
}

需要注意的是offset需要根据浏览器进行更改,除非有人能够找出导致它的原因。

我怀疑是letter-spacing还是类似的?