简体   繁体   English

我怎样才能模仿文本溢出:Firefox中的省略号?

[英]How can I mimic text-overflow: ellipsis in Firefox?

I have some dynamic text contained in a div that is set to whatever a user enters in a textbox field. 我有一些动态文本包含在div中,该div设置为用户在文本框字段中输入的内容。 If the text doesn't fit in the div, right now it just gets cut off at the edge and all the text that extends past the border is not visible. 如果文本不适合div,那么它现在只是在边缘切断,并且所有超出边框的文本都不可见。 I would like to truncate the text so that it fits inside the box and has an ellipsis (...) appended on the end. 我想截断文本,使其适合框内,并在末尾附加省略号(...)。 For example: 例如:

|----div width------|
 Here is some sample text that is too long.
 Here is some sam...

Obviously in the example it's easy because the code tag uses a fixed-width font so it's as simple as counting characters. 显然在示例中它很容易,因为代码标签使用固定宽度的字体,因此它就像计算字符一样简单。 I have a variable-width font so if they enter "WWWWWWWWWWW" it will fill up in much fewer characters than "................" would. 我有一个可变宽度的字体,所以如果他们输入“WWWWWWWWWWW”,它将填充比“................”更少的字符。

What's the best way to do this? 最好的方法是什么? I found a potential solution for simply finding the actual pixel width of the text here: http://www.codingforums.com/archive/index.php/t-100367.html 我发现了一个潜在的解决方案,可以在这里简单地找到文本的实际像素宽度: http//www.codingforums.com/archive/index.php/t-100367.html

But even with a method like that, it's a bit awkward to implement the ellipsis. 但即使使用这样的方法,实现省略号也有点尴尬。 So if it's 20 characters and I find that it doesn't fit, I would have to truncate to 19, add the ellipsis, and then check if it fits again. 因此,如果它是20个字符并且我发现它不适合,我将不得不截断为19,添加省略号,然后检查它是否再次适合。 Then truncate to 18 (plus the ellipsis) and try again. 然后截断为18(加上省略号)并再试一次。 And again. 然后再次。 And again...until it fit. 再次......直到它适合。 Is there a better way? 有没有更好的办法?

EDIT: I have decided based on the answers that my original approach is best, except I have tried to improve on the solution in the link above by not creating a separate td element simply for measuring, which feels like a hack. 编辑:我已经根据答案确定了我的原始方法是最好的,除了我试图通过不创建一个单独的td元素简单地用于测量来改进上述链接中的解决方案,这感觉就像一个黑客。

Here is my code: 这是我的代码:

<div id="tab" class="tab">
    <div id="tabTitle" class="tabTitle">
        <div class="line1">user-supplied text will be put here</div>
        <div class="line2">more user-supplied text will be put here</div>
    </div>
</div>

And styles: 和风格:

.tab {
padding: 10px 5px 0px 10px;
margin-right: 1px;
float: left;
width: 136px;
height: 49px;
background-image: url(../images/example.gif);
background-position: left top;
background-repeat: no-repeat;
}    

.tab .tabTitle {
    height: 30px;
width: 122px;
    overflow: hidden;
    text-overflow: ellipsis;
font-size: 12px;
font-weight: bold;
color: #8B8B8B;
}

.tab .tabTitle .line1, .tab .tabTitle .line2 {
    display:inline;
    width:auto;
}

and the javascript that trims and adds the ellipsis: 以及修剪和添加省略号的javascript:

function addOverflowEllipsis( containerElement, maxWidth )
{
    var contents = containerElement.innerHTML;
    var pixelWidth = containerElement.offsetWidth;
    if(pixelWidth > maxWidth)
    {
        contents = contents + "…"; // ellipsis character, not "..." but "…"
    }
    while(pixelWidth > maxWidth)
    {
        contents = contents.substring(0,(contents.length - 2)) + "…";
        containerElement.innerHTML = contents;
        pixelWidth = containerElement.offsetWidth;
    }
}

The "line1" and "line2" divs get passed to the function. “line1”和“line2”div传递给函数。 It works in the case of a single word input like "WWWWWWWWWWWWWWWWW" but does not work a multi-word input "WWWWW WWWWW WWWWW" because it just adds line breaks and measures the text as being the width of "WWWWW". 它适用于单字输入,例如“WWWWWWWWWWWWWWWWW”,但不能用于多字输入“WWWWW WWWWW WWWWW”,因为它只是添加换行符并将文本测量为“WWWWW”的宽度。

Is there a way I can fix this without resorting to copying the text into a hidden measuring element? 有没有办法解决这个问题,而无需将文本复制到隐藏的测量元素中? Some way to set the style of the line divs so that they don't wrap text? 某种方式设置行div的样式,以便它们不包装文本?

Some way to set the style of the line divs so that they don't wrap text? 某种方式设置行div的样式,以便它们不包装文本?

There you have the white-space: nowrap for. 那里有white-space: nowrap for。 Yes, this works in ancient browsers as well. 是的,这也适用于古老的浏览器。

This issue must be working on Firefox too. 这个问题也必须适用于Firefox。

HTML HTML

<div class="ellipsis">Here goes too long text and when it is takes more than 200px in "end" of the text appears "..."</div>

CSS CSS

.ellipsis{
width:200px;
text-overflow:ellipsis;
-o-text-overflow:ellipsis;
-moz-binding:url('bindings.xml#ellipsis');//issue for Firefox
}

bindings.xml bindings.xml

<bindings xmlns="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<binding id="none">
    <content><children/></content>
</binding>
<binding id="ellipsis">
    <content>
        <xul:label crop="end"><children/></xul:label>
    </content>
    <implementation>
        <field name="label">document.getAnonymousNodes(this)[0]</field>
        <field name="style">this.label.style</field>
        <property name="display">
            <getter>this.style.display</getter>
            <setter>if(this.style.display!= val)this.style.display=val</setter>
        </property>
        <property name="value">
            <getter>this.label.value</getter>
            <setter>if(this.label.value!=val)this.label.value=val</setter>
        </property>
        <method name="update">
            <body>
                var strings= this.textContent.split(/\s+/g)
                if(!strings[0])strings.shift()
                if(!strings[strings.length-1])strings.pop()
                this.value=strings.join('')
                this.display=strings.length?'':'none'
            </body>
        </method>
        <constructor>this.update()</constructor>
    </implementation>
    <handlers>
        <handler event="DOMSubtreeModified">this.update()</handler>
    </handlers>
</binding>
</bindings>

If you're using jQuery, there's a great plugin I use. 如果您正在使用jQuery,那么我使用的是一个很棒的插件

Alternatively, [this example] (404 NOT FOUND!) seems to work cross browser. 或者,[这个例子](404 NOT FOUND!)似乎可以跨浏览器工作。

Any questions, hit me up in the comments! 有任何问题,请在评论中打我!

404 link: http://www.hedgerwow.com/360/dhtml/text_overflow/demo2.php 404链接: http//www.hedgerwow.com/360/dhtml/text_overflow/demo2.php

The new version of CSS (CSS3) should include text-overflow:ellipsis , which does this for you. 新版本的CSS(CSS3)应该包括text-overflow:ellipsis ,它可以为您完成此操作。 It currently works in IE versions 6 and up, as well as Safari and Chrome. 它目前适用于IE版本6及更高版本,以及Safari和Chrome。 It's not supported by Firefox, so this isn't really a useful answer yet, but it's worth keeping in mind that the real best way will, eventually, be to let CSS handle this. Firefox不支持它,所以这还不是一个真正有用的答案,但值得记住的是,真正最好的方法最终将是让CSS处理这个问题。

CSS3 spec draft: http://www.w3.org/TR/2001/WD-css3-text-20010517/#text-overflow-props CSS3规范草案: http//www.w3.org/TR/2001/WD-css3-text-20010517/#text-overflow-props

Supported browsers: http://www.quirksmode.org/css/contents.html (scroll down to "text-overflow" near the bottom) 支持的浏览器: http//www.quirksmode.org/css/contents.html (向下滚动到底部附近的“文本溢出”)

Quite simply, no, there's no better way without resorting to hacks. 很简单,不,没有更好的方法,不诉诸黑客。

You could, for example, use a position:absolute span to position your "..." on top of the actual content, with overflow:hidden set on the container, and only hide the extra span if the content fits within the container. 例如,您可以使用一个位置:绝对跨度将“...”放在实际内容的顶部,并在容器上设置overflow:hidden,并且只有在内容适合容器内时才隐藏额外的跨度。 That'd let you run the truncation code only once. 这让你只运行一次截断代码。

Personally, I'd just run the pixel width calculation a few extra times. 就个人而言,我只需要多次运行像素宽度计算。 Setting the text and reading the width is a fast operation, so it shouldn't be noticeable. 设置文本和读取宽度是一个快速的操作,所以它不应该是显而易见的。

Use text-overflow:ellipsis . 使用text-overflow:ellipsis Its not IE-only... Most major browser can do this. 它不仅仅是IE ......大多数主流浏览器都可以做到这一点。
But if you can't here is a jQuery plugin for this. 但是,如果你不能在这里是一个jQuery插件

To answer just one of the points you raise: 要回答你提出的一点:

So if it's 20 characters and I find that it doesn't fit, I would have to truncate to 19, add the ellipsis, and then check if it fits again. 因此,如果它是20个字符并且我发现它不适合,我将不得不截断为19,添加省略号,然后检查它是否再次适合。 Then truncate to 18 (plus the ellipsis) and try again. 然后截断为18(加上省略号)并再试一次。 And again. 然后再次。 And again...until it fit. 再次......直到它适合。 Is there a better way? 有没有更好的办法?

A much faster way of finding the correct length is to cut the string in half, test that to see if it fits. 找到正确长度的更快的方法是将字符串切成两半,测试它是否适合。 If it does: add a quarter of the original length back on, and if it doesn't lop a quarter off, then test that to see if it fits. 如果是这样的话:重新加上原始长度的四分之一,如果它没有减掉四分之一,那么测试它是否适合。 Repeat recursively with 1/8th, 1/16th, 1/32th, ... of the original length, until this add/subtract value is less than 1. 以原始长度的1/8,1 / 16,1 / 32,...递归重复,直到此加/减值小于1。

It's a seeking algorithm: for strings that are longer than just a few words you can typically cut the number of tests you need to perform in the DOM by a factor of 10. 它是一种搜索算法:对于长度超过几个字的字符串,您通常可以将需要在DOM中执行的测试数量减少10倍。

Try this: 试试这个:

Link One 链接一

Update: 更新:

If you use the proprietary {word-wrap: break-word;}, IE will force a line break. 如果你使用专有的{word-wrap:break-word;},IE将强制换行。 Modern browsers could have the default {overflow: visible;}, and they would overflow properly, without expanding the container. 现代浏览器可能具有默认的{overflow:visible;},它们会正常溢出,而不会扩展容器。

No, it's not simple task. 不,这不是一项简单的任务。 I had to do same thing year ago and found that even Internet Explorer (from version 6), Opera and Safari can do it, but no Firefox. 我不得不在一年前做同样的事情,发现甚至Internet Explorer(从版本6),Opera和Safari都可以做到,但没有Firefox。 So sorry, only hacks can save you 很抱歉,只有黑客才能救你

使用Opera:

-o-text-overflow:ellipsis;

我从Binyamin的回复this.value=strings.join('')更改为this.value=strings.join(' ') ,这对我很有用!

About Firefox 4.0 and the, still unimplemented, text-overflow:ellipsis CSS property: 关于Firefox 4.0和仍未实现的text-overflow:ellipsis CSS属性:

This link gives a partial solution to the problem. 链接为问题提供了部分解决方案。

It produces a similar result to text-overflow:ellipsis using only css. 它产生类似于text-overflow:ellipsis结果text-overflow:ellipsis仅使用css。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM