Prevent background image flashing on change

走远了吗. 提交于 2019-12-11 16:55:52

问题


I'm using background image for a button and switch to a different one on :hover.

When the switch happens on the first mouse over it briefly flashes the background color. (I set it to orange here so it's more noticeable, it does the same with white background, or if I leave the background color unset). However, it does not flash on subsequent mouseovers.

How can I prevent the first flash of the background color that happens on page load, and first mouseover?

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>

回答1:


Load both images using multiple background and make the first one on the top then adjust background-size to show the other on hover. In this case, both images will be loaded initially and the second one will be ready on hover:

.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>



回答2:


Since the hover background image will not be pre-loaded, so that it shows the flashing effects especially for larger image size and longer loading time.

It can be fixed easily by using CSS sprites, e.g. combine the 2 background images into 1, and change the background-position on :hover, say the new image is 400px (200+200) height.

And, don't set any background-color to stop the initial flashing of the background color on page load. Also, width and height won't apply to inline-level a tag unless you change it to display: inline-block or block etc.

.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>

In addition, you don't need any images for gradient background, e.g.:

.backgroundbutton {
  background: linear-gradient(to right, #999, #fff);
}

.backgroundbutton:hover {
  background: linear-gradient(to right, #ccc, #fff);
}
<a class="backgroundbutton">hover over me</a>


来源:https://stackoverflow.com/questions/52358175/prevent-background-image-flashing-on-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!