图片延时加载jquery.inview.js用法详解

咱们在网站上总能见到这样的效果,如果有图片,图片都是先用loading加载一小段时间,而后紧接着出来要显示的图片,即效果以下:css

  v2_loading.gif,几秒钟时间过渡到v2_pic_01_s.jpg这样,这就是图片延时加载。html

具体实现技术以下:jquery

1)引入jquery库文件;web

2)引入jquery.inview.min.js文件;函数

3)html结构:网站

<a href="http://q.wan.com" target="_blank" title="秦时明月"><img src="http://static.wan.com/index/images/v2_pic_01_s.jpg" data-original="http://static.wan.com/index/images/v2_pic_01.jpg" alt="秦时明月" /></a> this

4)css样式:a{background-image: url(http://static.wan.com/index/images/v2_loading.gif);}url

5)script引用函数方法:spa

<script>
    $(function(){
      //延时加载页面图片。
      $('img[data-original]').live('inview', function(event, isVisible) {//这里要用live,不能用on;
        if (!isVisible) {
          return;
        }
        var img = $(this);
        // Show a smooth animation
        img.css('opacity', 0);
        img.load(function() {
          img.animate({
            opacity: 1
          }, 500);
        });
        // Change src
        img.attr('src', img.attr('data-original'));
        // Remove it from live event selector
        img.removeAttr('data-original');
      });
    });
    </script>

以上步骤便可实现该效果。code

相关文章
相关标签/搜索