溢出:隐藏。在js / jquery中,将隐藏文件与可见文本进行比较

时间:2013-09-05 20:42:29

标签: javascript jquery

如果我有一个溢出:隐藏容器如下所示,有没有办法让我通过js / jquery找出哪些文字是可见的,哪些文字是隐藏的?

div{
    height:2.4em;
    line-height:1.2em;
    overflow:hidden;
    width:100px;
    background:pink;   
}

<div>
    I am some text and more text and so on and on I just keep going.
</div>

2 个答案:

答案 0 :(得分:0)

只知道我拥有的东西:

<div>
    <span>I am some text and more text and so on and on I just keep going.</span>
</div>

删除字母,直到span大于div:P(您使用element.offsetHeightelement.offsetWidth$(element).height$(element).width

答案 1 :(得分:0)

考虑到包装和线高,棘手的部分是找出多少适合于单词的基础。写了一个小的jquery插件。这是片段,

$.fn.visibleText = function () {
    // Get the currents
    var currWidth = this.width();
    var currHeight = this.height();
    var htmlContent = this.html();


    var lineHeight = parseFloat(this.css("lineHeight"), 10);
    // Need to calculate the number of lines visible
    // as currHeight < numLines * lineHeight, at times
    // Eg: Try changing height to 4.4em and width to 110px
    var numLines = Math.round(currHeight / lineHeight);
    var actualHeight = (numLines * lineHeight);

    // Clearing
    this.html("");
    this.height("initial");

    // Push to HTML until hitting the terminating conditions
    // currWordLength is required since wrapping of a word could push
    // to the line
    var vContent = "",
        currWordLength = 0;
    while (this.height() <= actualHeight) {
        var currChar = htmlContent[vContent.length];
        vContent += currChar;
        this.html(vContent);
        if (currChar === " ") {
            currWordLength = 0;
        }
        currWordLength++;
        if (htmlContent.length === vContent.length) {
            currWordLength = 0;
            break;
        }
    }
    var visible = vContent.substring(0, vContent.length - currWordLength);

    // Revert to originals
    this.height(currHeight);
    this.html(htmlContent);
    return {
        visible: visible,
        hidden: htmlContent.substring(visible.length, htmlContent.length)
    }
};

http://jsfiddle.net/aravindbaskaran/v2ECm/

处摆弄它