我正在使用背景图像作为按钮,并切换到:hover
上的另一个。
当第一只鼠标在其上方发生切换时,它会短暂闪烁背景颜色。 (我在这里将它设置为橙色,因此它更明显,它与白色背景相同,或者如果我不设置背景颜色)。但是,它不会在后续的鼠标悬停时闪烁。
如何防止页面加载时首次闪现背景颜色,并首先将鼠标悬停?
https://codepen.io/ClayN/pen/EeeRyP
.backgroundbutton {
background-image: url('http://www.BungalowSoftware.com/images/silver-background.jpg');
width: 100px;
height: 30px;
background-color: orange;
}
.backgroundbutton:hover {
background-image: url('http://www.BungalowSoftware.com/images/silver-background2.jpg')
}
<a class="backgroundbutton">hover over me</a>
使用多个背景加载两个图像并将第一个放在顶部然后调整background-size
以在悬停时显示另一个。在这种情况下,两个图像最初都会加载,第二个图像将在悬停时准备就绪:
.backgroundbutton {
background-image:
url('http://www.BungalowSoftware.com/images/silver-background.jpg'),
url('http://www.BungalowSoftware.com/images/silver-background2.jpg');
background-size:auto;
width: 100px;
height: 30px;
background-color: orange;
}
.backgroundbutton:hover {
background-size:0 0,auto;
}
<a class="backgroundbutton"> hover over me</a>
由于悬停背景图像不会被预先加载,因此它会显示闪烁效果,尤其是对于较大的图像尺寸和较长的加载时间。
它可以通过使用CSS精灵轻松修复,例如将2个背景图像合并为1,并更改background-position
上的:hover
,比如说new image的高度为400px(200 + 200)。
并且,不要设置任何background-color
来停止页面加载时背景颜色的初始闪烁。此外,width
和height
将不适用于内联级别的a
标签,除非您将其更改为display: inline-block
或block
等。
.backgroundbutton {
background: url("https://i.imgur.com/lrlOvEP.png") 0 0 no-repeat;
}
.backgroundbutton:hover {
background-position: 0 -200px;
}
<a class="backgroundbutton">hover over me</a>
此外,您不需要任何渐变背景图像,例如:
.backgroundbutton {
background: linear-gradient(to right, #999, #fff);
}
.backgroundbutton:hover {
background: linear-gradient(to right, #ccc, #fff);
}
<a class="backgroundbutton">hover over me</a>