jquery 延时加载dom节点

/*
用法:
<div id="dataContainer">
    <textarea class="data-lazyload">
        <p>lazyload的数据,里面的textarea标签要转义,要么会textarea嵌套textarea出错。</p>
        <p>lazyload的数据js加进去的,所以不能用bind绑定事件,用live或delegate</p>
        <div><h1>ddd</h1></div>
        <div>            
            &lt;textarea&gt;转义后的textarea&lt;/textarea&gt;
        </div>
    </textarea>
</div>

一、进入可视区加载dom数据
$("#dataContainer").dataLazyLoad();

二、事件加载dom数据
$(".btn").click(function(){
$("#dataContainer").lazyLoadData();
});
*/

(function ($) {
    var defaults = {
        defHeight: 0,
        dataObjClass: "data-lazyload"
    },
    init = false;

    $.fn.extend({
        dataLazyLoad: function (option) {
            var opt = $.extend(defaults, option || {});
            var scrollH, //滚动高度
            viewH, //进入可视区高度
            _this = this;
            scrollH = (navigator.userAgent.toLowerCase().match(/iPad/i) == "ipad") ? window.pageYOffset : Math.max(document.documentElement.scrollTop, document.body.scrollTop);
            viewH = document.documentElement.clientHeight + scrollH - opt.defHeight;
            _this.each(function () {
                if (!$(this).attr("data-lazyload") && $(this).offset().top <= viewH) {
                    _loadData($(this), $("." + opt.dataObjClass));
                }
            });
            if (!init) {
                init = true;
                $(window).bind("scroll resize",
            function () {
                _this.dataLazyLoad(opt);
            });
            }

        },
        lazyLoadData: function (option) {
            var opt = $.extend(defaults, option || {});
            this.each(function () {
                if (!$(this).attr("data-lazyload")) {
                    _loadData($(this), $("." + opt.dataObjClass));
                }
            });
        }
    });

    var _loadData = function (container, dataDom) {
        var dataHtml = dataDom.val();
        container.attr("data-lazyload", "loaded").find(dataDom).before(dataHtml);
        dataDom.remove();
    };
} (jQuery));

posted on 2012-10-08 11:55  lzf0514  阅读(483)  评论(0编辑  收藏  举报

导航