在HTML中隐藏溢出文本的中间部分

Luu*_*ukV 9 html html5

是否可以隐藏溢出文本的中间而不是结尾?例如用句点替换溢出的文本.

我现在在桌子上专门谈论,但任何可能的方式都会很有用.

所以我的意思是缩短112233445566778899112...899(或类似的东西)而不是11223344

我不太了解JavaScript,但如果这是唯一的方式让我知道如何,我将通过教程找出其余部分.

Jam*_*lly 5

我想出了一个纯粹的JavaScript解决方案,它将Nick Ralhoseany的答案结合在一起,同时添加了一些额外的功能来检测长度并指定省略号两边所需的字符数.

使用此方法,您无需知道容器中可容纳的字符数,它们全部自动完成,也可以在窗口调整大小时触发.

JSFiddle演示.

调整结果框的大小以查看结果.

结果

这个:

初始例子

......变成这个:

例

...或这个:

例2

...或这个!

例3

代码

CSS

p {
    border: 1px dashed #000;
    position: relative;
    display: block;
    width: 50%;
}

p:before {
    content:attr(data-shortened);
    color: #000;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript的

function shortenContent(content, chars) {
    /* chars here determines how many characters
     * we want on either side of the elipsis. */
    var chars = chars || 3; // Default is 3

    if (!content && !content.length)
        return;

    /* Loop through each content element and
     * shorten where necessary. */
    for (i = 0; i < content.length; i++) {
        var el = content[i],
            elementWidth = el.offsetWidth,
            textWidth = el.scrollWidth;

        /* If our element's width is less than
         * its content's width, we need to shorten. */
        if (elementWidth < textWidth) {
            var text = el.innerText;
            /* Set the data attribute for the CSS to use. */
            el.setAttribute(
              'data-shortened', text.slice(0,chars) +'...'+ text.slice(-chars)
            );
            el.style.color = 'rgba(0, 0, 0, 0)';
        }
        /* Otherwise, ensure non-shortened text is visible. */
        else {
            el.setAttribute('data-shortened', '');
            el.style.color = null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何使用它?

要使用上面的函数,您只需要将一组元素传递给shortenContent函数:

// Get the content we wish to shorten
var content = document.querySelectorAll('div p');

/* Trigger the function initially. */
shortenContent(content);
Run Code Online (Sandbox Code Playgroud)
abcdefghijklmnopqrstuvwxyz    =>    abc...xyz
Run Code Online (Sandbox Code Playgroud)

指定不同数量的字符

如果你想在省略号之前和之后出现不同数量的字符(例如,abcd...wxyz而不是abc...xyz),你可以将一个数字作为第二个参数传入shortenContent函数:

/* Trigger the function initially. */
shortenContent(content, 4);
Run Code Online (Sandbox Code Playgroud)
abcdefghijklmnopqrstuvwxyz    =>    abcd...wxyz
Run Code Online (Sandbox Code Playgroud)

Window Resize示例

shortenContent每当窗口(在这种情况下为JSFiddle结果窗格)改变大小时,这将触发该函数.

/* Fire the shorten function when the window resizes. */
window.onresize = function(event) {
    shortenContent(content);
};
Run Code Online (Sandbox Code Playgroud)