JavaScript - DIV的可见文本 [英] JavaScript - Visible Text of a DIV

查看:172
本文介绍了JavaScript - DIV的可见文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

----------------------------------------------------
| This is my text inside a div and I want the overf|low of the text to be cut
----------------------------------------------------

请注意我希望删除溢出,因此CSS省略号属性对我不起作用。基本上,我希望上面的文字显示如下:

Please note that I want the overflow to be removed, so the CSS ellipsis property would not work for me. So basically, I want that the text above to appear like this:

----------------------------------------------------
| This is my text inside a div and I want the overf|
----------------------------------------------------

纯JavaScript如何实现这一目标?

How is this possible with pure JavaScript?

编辑

我需要一个JavaScript函数来裁剪文本,因为我需要计算可见的字符数文本。

I need a JavaScript function to crop the text because I need to count the characters of the visible text.

推荐答案

好的,我没有看到问题的附录。虽然我之前曾说过使用JavaScript和非固定宽度的字体是不可能做到这一点的......实际上 是可能的!

Okay, I didn't see the addendum to the question. Although I had previously said it wasn't possible to do this using JavaScript and a font that isn't fixed-width... it actually is possible!

您可以将每个字符包装在< span> 中,然后找到第一个< span> 超出父母的界限。类似于:

You can wrap each individual character in a <span>, and find the first <span> that is outside the bounds of the parent. Something like:

function countVisibleCharacters(element) {
    var text = element.firstChild.nodeValue;
    var r = 0;

    element.removeChild(element.firstChild);

    for(var i = 0; i < text.length; i++) {
        var newNode = document.createElement('span');
        newNode.appendChild(document.createTextNode(text.charAt(i)));
        element.appendChild(newNode);

        if(newNode.offsetLeft < element.offsetWidth) {
            r++;
        }
    }

    return r;
}

这是一个演示。

这篇关于JavaScript - DIV的可见文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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