jQuery消極式載入(懶載入)外掛程式 – jquery.lazyload.js

來源:互聯網
上載者:User

標籤:each   target   logs   hive   src   bsp   this   ase   ref   

http://www.w3cways.com/1765.html

http://www.cnblogs.com/tinyphp/archive/2013/04/09/3009385.html

 

jquery外掛程式的寫法,以及requireJS如何引入jquery外掛程式

下面,就是一個自製的jQuery小外掛程式(affix),用於固定某個元素在瀏覽器頂部(也可以自訂距離瀏覽器頂部多高的位置),不隨捲軸的下拉而移動

;(function(){    $.fn.extend({            ‘affix‘:function(opt){                var DEFAULT = {                    ‘offLeft‘:‘0‘,                    ‘offT‘:‘0‘                };                var options = $.extend({},DEFAULT,opt);                this.each(function(){                    var obj = $(this);                    var offTop = obj.offset().top;                    $(window).bind(‘scroll‘,checkTop);                    function checkTop(){                        var scrollT = $(window).scrollTop();                        if(scrollT >= offTop) {                            obj.css({‘position‘:‘fixed‘,‘left‘:‘0‘,‘top‘:options.offT});                        } else {                            obj.css({‘position‘:‘static‘});                        }                    }                });        }    });})($)

這個外掛程式是一個符合jquery外掛程式規範的,大家可以參照這種jquery外掛程式的寫法,來封裝自己的外掛程式。

那麼在requireJS中,如何使用呢? 
<script src="js/require-2.1.11.js" data-main="js/main"></script> 
在我們的項目中引入requireJS,data-main="js/main" 
main.js就是我們項目中js檔案的入口檔案

require.config({    paths:{        ‘jquery‘: [            ‘https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min‘,            ‘https://cdn.bootcss.com/jquery/2.1.4/jquery.min‘        ]    },    shim:{        ‘affix‘:{            deps:[‘jquery‘]        }    }});require([‘affix‘],function(){    $(‘.subnav‘).affix();    $(‘.aside‘).affix();});

因為affix是一個深度依賴jquery的小外掛程式,所以我們在require中引入affix的時候,需要先配置affix的依賴項

shim:{    ‘affix‘:{        deps:[‘jquery‘]    }}

那麼頁面中class為subnav和aside的元素,當捲軸往下拉的時候 ,元素滾動頁面頂部的時候,就會被定住,不會繼續往上滾動了。

 

require.config({
paths : {
"jquery": ["/static/lib/jquery.min"],
"jquery.lazyload": ["/static/lib/jquery.lazyload"],
"header":["/static/ns/js/header"],
},
shim:{
‘jquery.lazyload‘:{
deps:[‘jquery‘]
}
}
});
function getvipLevelClass(vip){
return ‘u-level-0‘+vip;
}
require([‘jquery‘,‘header‘,‘jquery.lazyload‘],function($,header){
$(function(){
header.init();
$("img.lazy").lazyload();
})
});

 

jQuery消極式載入(懶載入)外掛程式 – jquery.lazyload.js

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.