很多网站的按钮都是通过 JavaScript 改变背景图片来实现的,例如:
style="width:70px; height:35px; background:url(bg.jpg);"
οnmοuseοver="this.style.background='url(bg2.jpg)'" οnmοuseοut="this.style.background='url(bg.jpg)'">
这样的坏处是,比较费资源,频繁在按钮上晃,你会发现CPU使用会高很多。
用CSS可以避免这样的问题。下图是示例图片bg.jpg,两张切换的背景连着一张图片,这样可以避免切换时还要下载另一张背景图片。
代码如下:
.button a {
width:70px;height:35px; background: url(bg.jpg) 0 0 no-repeat;
}
.button a:hover {
background: url(bg.jpg) 0 -35px no-repeat;
}
上面代码的核心是:
background
: background-color || background-image || background-repeat || background-attachment || background-position
background-position
: length || length
background-position
: position || position
取值:
length
: 百分数 | 由浮点数字和单位标识符组成的长度值。
position
: top | center | bottom | left | center | right
简单点讲就是鼠标移到图片上后,背景使用图片的下半部分。
转自http://lintex.blog.sohu.com/86027591.html
但是很多时候我们是这样用的:加入有两个按钮,一个向左,一个向右,那么怎么让它们显示我们所想要的图片呢?
.prevPhoto input, .nextPhoto input {
background:transparent url(../../images/photoPager_bg.gif) no-repeat scroll0 0
;
border:0 none;
cursor:pointer;
display:block;
float:left;
height:19px;
margin:0 auto;
overflow:hidden;
padding:0;
text-indent:-9999px;
width:72px;
}
注意看红色加粗部分,我没有像之前那样将背景分别加载,而是将左右按钮放到了一起,那么该如何选择需要显示的图片呢?
.prevPhoto input {
background-position:0 -20px;
float:left;
}
.nextPhoto input {
background-position:0 -40px;
float:right;
}
上面的大家应该都能看懂的,这里有一个必须要提醒大家,就是
.prevPhoto input
和.nextPhoto input
必须在
.prevPhoto input, .nextPhoto input
后面
。