Javascript preload images for css background-image change

前端 未结 4 1168
猫巷女王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 06:40

    you can use this solution. http://www.gayadesign.com/diy/queryloader-preload-your-website-in-style/

    0 讨论(0)
  • 2021-01-15 06:55

    Stack your images as one image, and then add a class that shifts the image's background property to the appropriate offset.

    Not only does this turn multiple images into one HTTP request, it also means you don't have to bother writing code to preload the hover state of the images.

    This is called a sprite sheet.

    0 讨论(0)
  • 2021-01-15 07:00

    pretty simple to preload images, something like:

    var img = new Image();
    img.src = "/path/to/image.jpg";
    

    This could be in a window.load or dom:ready event somewhere

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题