按钮点击启动延迟加载

时间:2017-01-19 13:36:36

标签: javascript

我点击按钮时试图让它工作。这样做的目的是一个简单的轻量级lazyload,它在单击过滤器按钮时有效。

目前我无法使用按钮进行此操作。

<ul>
    <li class="sort" data-sort="default" onclick="sort();">Default</li></li>
    <li class="sort" data-sort="top-ten:asc" onclick="sort();">Most Popular (1 - 10)</li>
    <li class="sort" data-sort="top-ten:desc" onclick="sort();">Most Popular (10 - 1)</li>
    <li class="sort" data-sort="name:asc" onclick="sort();">Name Ascending (a - z)</li>
    <li class="sort" id="sort" data-sort="name:desc" onclick="lazyLoad();">Name Descending (z - a)</li>
    <li class="sort" data-sort="random" onclick="sort();">Random</span></li>
</ul>

<script>
var lazy = [];
registerListener('load', setLazy);
registerListener('load', lazyLoad);
registerListener('scroll', lazyLoad);
registerListener('resize', lazyLoad);

document.getElementById('sort').addEventListener('click', function() {

});

function setLazy(){
    lazy = document.getElementById('img-loading').getElementsByTagName('img');
    // console.log('Found ' + lazy.length + ' lazy images');
} 

function lazyLoad(){
    console.log('lazyLoad initiated');
    for(var i=0; i<lazy.length; i++){
        if(isInViewport(lazy[i])){
            if (lazy[i].getAttribute('data-src')){
                lazy[i].src = lazy[i].getAttribute('data-src');
                lazy[i].removeAttribute('data-src');
            }
        }
    }
    cleanLazy();
    console.log('lazyLoad END');
}

function cleanLazy(){
    lazy = Array.prototype.filter.call(lazy, function(l){ return l.getAttribute('data-src');});
}

function isInViewport(el){
    var rect = el.getBoundingClientRect();

    return (
        rect.bottom >= 0 && 
        rect.right >= 0 && 
        rect.top <= (window.innerHeight || document.documentElement.clientHeight) && 
        rect.left <= (window.innerWidth || document.documentElement.clientWidth)
     );
}

function registerListener(event, func) {
    if (window.addEventListener) {
        window.addEventListener(event, func)
    } else {
        window.attachEvent('on' + event, func)
    }
}
</script>

0 个答案:

没有答案