占一个HTML DIV的长度截断文本 [英] Accounting for the length of an HTML DIV for truncating text

查看:122
本文介绍了占一个HTML DIV的长度截断文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< D​​IV> 我正在与不确定的大小的文件名称填写。如果大小超过了&LT的长度; DIV> 然后,我希望它砍下来,用...取代了最后3个字符。目前,我有以下几点:

I have a <div> that I'm filling with a file name of indeterminable size. If the size exceeds the length of the <div> then I want it to be cut down and the last 3 characters replaced with a "...". Currently I have the following:

<div id="fileName" class="field-row" title="<%= fileName %>">
    <% if(fileName.Length > 20) { %>
        Filename: <%= fileName.Substring(0,20) %>...
    <% } else { %>
        Filename: <%= fileName %>
    <% } %>
</div>

这工作正常,但如果我有一个是由我的主场迎战的文件名W公司则在div将右边未使用的空间。

This works fine but if I have a file name that is made up of i's vs. W's then the div will have unused space on the right.

例如:

iiiiiiiiii.jpg

"iiiiiiiiii.jpg"

短于:

WWWWWWWWWW.jpg

"WWWWWWWWWW.jpg"

...即使它们具有相同的字符数。

...even though they have the same number of characters.

有没有更好的方式来做到这一点占的长度&LT; D​​IV&GT;

Is there a better way to do this that accounts for the length of the <div>?

感谢您,

亚伦

推荐答案

,它应该做客户端。

下面是一个大部分,跨浏览器的,大多是CSS的方式来做到这一点:的http:/ /www.electrictoolbox.com/ellipsis-html-css/ 。这不是完全的支持,但是这是JavaScript的回退是什么。*基本上,只要用

Here's a mostly-cross-browser, mostly-CSS way to do it: http://www.electrictoolbox.com/ellipsis-html-css/. It's not totally supported, but that's what the JavaScript fallback is for.* Basically, just use

#fileName {
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
}

没有任何JavaScript,这让你对IE7-,Safari /铬,歌剧,Konqueror的。

Without any JavaScript, that gets you support for IE7-, Safari/Chrome, Opera, Konqueror.

http://www.quirksmode.org/css/textoverflow.html

如果您觉得使用JavaScript只是为了支持Firefox太哈克,你可以用纯CSS棒,和四溢的文本将只是被隐藏。尝试查看在FF怪异模式页面,你会看到。

If you feel that using JavaScript just to support Firefox is too hacky, you can stick with the pure CSS, and the overflowing text will simply be hidden. Try viewing the quirksmode page in FF and you'll see.

*的编辑:的后已经测试的的jQuery插件省略号FireFox的补丁,我可以证实它的工作原理相当不错,和伸缩能力非常好,如果您不使用实时调整大小(唯一的)选择与所有26个元素和现场的选项,调整了火狐 - 仡机上 - 下屈服。谨慎使用这个选项!这是一个不错的方便,但该插件看起来并不被非常有效地写入(我没有时间来修补它现在)。

* after having tested the jQuery ellipsis plugin patch for FireFox, I can confirm it works quite nicely, and scales well enough, if you don't use the "live resize" (the only) option. With all of 26 elements and the live option, resizing took FireFox - on a beefy machine - down to its knees. Be careful with this option! It's a nice convenience, but the plugin does not look to be written terribly efficiently (and I don't have time to patch it right now).

这篇关于占一个HTML DIV的长度截断文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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