hover的时候预加载图片

 
<!DOCTYPE html>
<html>
     <head>
           <meta charset="UTF-8">
           <title></title>
           <script src="js/jquery-1.11.2.min.js" type="text/javascript" charset="utf-8"></script>
           <style>
                span{cursor: pointer;margin: 5px;display: inline-block;}
                span.active{color:red;}
                img{display: none;}
                img.active{display: block;}
           </style>
     </head>
     <body>
           <span class="active">图片1</span>
           <span>图片2</span>
           <span>图片3</span>
           <br />
           <img src="img/mm1.jpg" alt="" class="active"/>
           <img data-src='img/mm2.jpg' />
           <img data-src='img/mm3.jpg' />
     </body>
     <script type="text/javascript">
           $('span').each(function(index){
                $(this).data('index',index).click(function(){
                     _img = $('img').eq($(this).data('index')); //获取与span对应的img;
                     $(this).addClass('active').siblings('span').removeClass('active');
                     _img.addClass('active').siblings('img').removeClass('active');
                })
           });
           $('span').on({
                mouseenter:function(){
                     var _Img = $('img').eq($(this).data('index'));  //获取与span对应的img;
                   if (!this.preloaded) { //preloaded自定义变量,  一上来的时候没有定义该值,所以是undefined,!undefined为true;
                       // 图片地址换成真实地址
                       _Img.attr('src', _Img.attr('data-src')).removeAttr('data-src');
                       // 标记已加载
                       this.preloaded = true; //这设置为true,去反就是false;就进不了if
                   }
                }
           });
     </script>
</html>
 

  

 

posted @ 2020-10-10 16:42  三只小熊sky  阅读(223)  评论(0)    收藏  举报