Javascript preload images for css background-image change

前端 未结 4 1167
猫巷女王i
猫巷女王i 2021-01-15 06:16

I am developing a website which requires the background image of a div to change on hover of a link.

The way it works is by:



        
4条回答
  •  迷失自我
    2021-01-15 07:01

    You can make a sprite image, i.e. put the two images together into one. Then you just change the background position to show the other part of the image. If the element is for example 20 pixels high, you move the background position by 20 pixels:

    function hoverClear(){
      $('.navReflect').css("background-position", "0 0");
    }
    
    function hover(hover){
      $('.navReflect').css("background-position", "0 -20px");
    }
    

    As it's only a single image, the alternate look is loaded from the start. This will also reduce the number of requests to the server.

    You can ever put more images together like this. You can see an example at the top right corner of my website, where a single image is used for two different flags each in two different states.

提交回复
热议问题