WEB2.0 web20
当前位置:首页 > 网站建设专题 > WEB2.0
哪些情况下需要CSS隐藏文字?
发布日期:2009-08-27 阅读次数:816 字体大小:

今天在做一个页面的时候,遇到一个常见的问题,切图是否连文字一起切了。如果只切背景,文字的效果用css无法实现;如果连文字一起切,文本就为空,这样在抛开css裸奔的情况下就不能很顺利的汲取到页面信息,不利于SEO。

所以就想到了,连文字一起切,用css隐藏文字的解决办法。还有一种常见的需要隐藏文字的,就是文字的字段长度超出了容器的宽度,需要隐藏。以前写过解决办法:

两种方法实现超出省略号效果

纯css方法:

以下为引用的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS test</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
body{
padding:10px;
font-family:Arial;
}
#ididid{
position:relative;
width:150px;
height:20px;
line-height:20px;
text-overflow:ellipsis;
white-space:normal;
*white-space:nowrap;
overflow:hidden;
border:1px solid #999;
}
#ididid span{
position:absolute;
top:0;
right:0;
display:block;
float:left;
}
#ididid span:after{content:"...";}
</style>
</head>
<body>
<div id="ididid">woaicss woaicss woaicsswoaicsswoaicsswoaicss<span></span></div>
</body>
</html>

js判断:

以下为引用的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS test</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
body{
padding:10px;
font-family:Arial;
}
#ididid{
width:150px;
line-height:20px;
overflow:hidden;
border:1px solid #999;
}
</style>
</head>
<body>
<script type="text/javascript">
function testAuto(thisId,needLeng){
var ididid = document.getElementById(thisId);
var nowLeng = ididid.innerHTML.length;
if(nowLeng > needLeng){
var nowWord = ididid.innerHTML.substr(0,needLeng)+'...';
ididid.innerHTML = nowWord;
}
}
</script>
<div id="ididid">2323232woaicsswoaicsswoaicsswoaicss</div>
<script type="text/javascript">
testAuto('ididid',15)
</script>
</body>
</html>

这里说下第一种情况的解决方法。

1.在容器里面加个标签span,然后用display:none;兼容性比较好。但是会多个标签,如果循环使用的话,会多一堆html代码,单个图片或者按钮推荐使用。

如果是要隐藏input 的value用这种方法就不好实现。所以就有了第二种方法:

2.使用text-indent:-9999px;

它也有个局限性,就是只能用于块状元素(block),如果我们想偏移掉a上的字体,问题就出来了:为了偏移文字要改变a的 为block,这样a后面的元素要到下一行了,要再用float来避免,这样未免有点麻烦。

3.下面这种方法自己比较常用:

line-height:0;

font-size:0;

overflow:hidden;

能完美“隐藏”掉你background之上的字体,兼容性也比较好,经测试 ie6.0 、 7.0 、8.0、firefox 3.010 通过。

当然要根据具体的情况,没有最好的只有最合适的。

蜗牛供稿:http://www.woaicss.com

kukuyu55