jQuery callback on image load (even when the image is cached)

前端 未结 14 1423
轻奢々
轻奢々 2020-11-21 06:25

I want to do:

$(\"img\").bind(\'load\', function() {
  // do stuff
});

But the load event doesn\'t fire when the image is loaded from cache

14条回答
  •  半阙折子戏
    2020-11-21 07:22

    If you want a pure CSS solution, this trick works very well - use the transform object. This also works with images when they're cached or not:

    CSS:

    .main_container{
        position: relative;
        width: 500px;
        height: 300px;
        background-color: #cccccc;
    }
    
    .center_horizontally{
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: green;
      left: 50%;
      top: 0;
      transform: translate(-50%,0);
    }
    
    .center_vertically{
      position: absolute;
      top: 50%;
      left: 0;
      width: 100px;
      height: 100px;
      background-color: blue;
      transform: translate(0,-50%);
    }
    
    .center{
      position: absolute;
      top: 50%;
      left: 50%;
      width: 100px;
      height: 100px;
      background-color: red;
      transform: translate(-50%,-50%);
    }
    

    HTML:

    Codepen example

    Codepen LESS example

提交回复
热议问题