用省略号代替span中的长文字。
1. 通过CSS控制
- <html>
- <head>
- <style type="text/css">
- body{
- font-family:Arial, Helvetica, sans-serif;/* 字体 */
- font-size:12px;/* 字体大小12像素 */
- }
- a{
- width: 140px;/* 要显示文字的宽度 */
- float: left;/* 左对齐,不设置的话只在IE下好用 */
- overflow: hidden; /* 超出的部分隐藏起来 */
- white-space: nowrap;/* 不显示的地方用省略号...代替 */
- text-overflow: ellipsis;/* 支持 IE */
- -o-text-overflow: ellipsis;/* 支持 Opera */
- }
- </style>
- </head>
- <body>
- <a href="#">CSS截取字符串,超出用省略号代替</a>
- </body>
- </html>
通过CSS控制不需要改变文本本身,可以在页面渲染的时候就控制如何显示了,并且可以通用,缺点是只能在文字尾部加省略号,但有的时候我想要这种格式,“测试-看我有多长看我....doc”,如果文本过长的话,.doc前的文本加省略号,保留格式标志,这种CSS就无法控制了。
2. 通过改变要显示的文本,前提是动态网站,思路是后台语言取得文本内容后,在显示在前台前,根据页面当前字体样式动态改变文本。
- Font font = new Font("SansSerif", Font.PLAIN, 12);
- Button button = new Button();
- FontMetrics metrics = button.getFontMetrics(font);
-
- String info = "CSS截取字符串,超出用省略号代替";
- String temp = info;
- while(metrics.stringWidth(temp) > 140) {
- temp = temp.substring(0, temp.length() - 1);
- }
- System.out.println(temp + "...");
这是用AWT算的,这种方式有点2。
3. 通过JavaScript计算
- function test() {
- var info = "CSS截取字符串,超出用省略号代替";
- var temp = info;
- while(getTextWidth(temp) > 140) {
- temp = temp.substring(0, temp.length - 1);
- }
- console.log(temp + "...");
- }
-
- function getTextWidth(info) {
- var width;
- var textNode = document.createTextNode(info);
- var spanNode = document.createElement("span");
- spanNode.appendChild(textNode);
- document.body.appendChild(spanNode);
- width = spanNode.offsetWidth;
- document.body.removeChild(spanNode);
- return width;
- }
这种方式是根据文本动态创建一个span,从而得到文本宽度,效率应该很低。