我尝试在用户点击按钮时启动功能。
此时它会在加载网站时以及用户滚动或调整浏览器大小时启动。但是,当用户点击特定按钮时,如何让它工作。在妈妈的按钮上有一个onclick =" sort();"。
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)
}
}
答案 0 :(得分:0)
var button=document.getElementById('button'),
clickFunction=function(button){
alert('click');
};
button.addEventListener('click',clickFunction);
<input id="button" type="button" value="test">