HTML   发布时间:2022-04-15  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在HTML中隐藏溢出文本的中间大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以隐藏溢出文本的中间而不是结束?例如用句点替换overflown文本.

我现在正在谈论一个表,但任何可能的方式将是很好的知道.

所以我的意思是缩短112233445566778899到112 … 899(或类似的东西),而不是11223344

我不太了解JavaScript,但如果这是让我知道的唯一方法,我会用教程找出其余的内容.

解决方法

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

使用这种方法,您不需要知道容纳在容器中的字符数,它们都是自动完成的,并且也可以在窗口调整大小时触发.

JSFiddle demo.

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

结果

这个:

…成为这样

…或这个:

…或这个!

代码

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

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)';
        }
        /* Otherwise,ensure non-shortened text is visible. */
        else {
            el.setAttribute('data-shortened','');
            el.style.color = null;
        }
    }
}

如何使用?

要使用上述函数,只需要将一个元素集合传入shortenContent函数:

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

/* trigger the function initially. */
shortenContent(content);
abcdefghijklmnopqrstuvwxyz    =>    abc...xyz

指定不同数量的字符

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

/* trigger the function initially. */
shortenContent(content,4);
abcdefghijklmnopqrstuvwxyz    =>    abcd...wxyz

窗口调整大小示例

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

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

大佬总结

以上是大佬教程为你收集整理的在HTML中隐藏溢出文本的中间全部内容,希望文章能够帮你解决在HTML中隐藏溢出文本的中间所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。