2017-06-12 51 views
0

我有一个元素,它应该根据文档属性调整宽度+高度。我需要调整用户在窗口内滚动的时间。将事件绑定到普通JavaScript中的对象

是否有可能将事件绑定到此特定对象?

var instance = (function() { 
 
    var w = window, 
 
    d = document, 
 
    e = d.documentElement, 
 
    g = d.getElementsByTagName('body')[0], 
 
    x = w.innerWidth || e.clientWidth || g.clientWidth || 0, 
 
    y = w.innerHeight || e.clientHeight || g.clientHeight || 0, 
 
    z = Math.max(g.scrollHeight || 0, e.scrollHeight || 0, g.offsetHeight || 0, e.offsetHeight || 0, g.clientHeight || 0, e.clientHeight || 0); 
 

 
    // private 
 
    function getMeById(id) { 
 
    return d.getElementById(id); 
 
    }; 
 

 
    // public 
 
    return { 
 
    updateContainer: function(id) { 
 
     console.log('updateContainer'); 
 
     var container = getMeById(id); 
 
     container.style.position = 'absolute'; 
 
     container.style.width = x + 'px'; 
 
     container.style.minHeight = z + 'px'; 
 
    }, 
 
    bindScroll: function() { 
 
     w.addEventListener('scroll', updateContainer(), false); 
 
    } 
 
    }; 
 

 
})(); 
 
instance.updateContainer("test"); 
 

 
/* @TODO: Bind events to object 
 
    w.addEventListener('resize',() => { 
 
    console.log('resize'); 
 
    var container = getMeById("test"); 
 
    updateContainer(container); 
 
    }, true); 
 

 
    w.addEventListener('scroll',() => { 
 
    console.log('scroll'); 
 
    var container = getMeById("test"); 
 
    updateContainer(container); 
 
    }, true); 
 
    */
<div id="test"></div>

你可以从看到 “bindScroll()” - 它的作用是没有意义的现在。 无论如何要完成任务吗?

非常感谢您的帮助。

+0

变量'w'只存在于封闭,而不是在全球范围内您的注释的代码。 'window.addEventListener'应该可以做到。 – Aloso

回答

1

,您可以通过它绑定到updateContainer通标识加入事件监听回调:

updateContainer: function(id) { 
    console.log('updateContainer'); 
    var container = getMeById(id); 
    container.style.position = 'absolute'; 
    container.style.width = x + 'px'; 
    container.style.minHeight = z + 'px'; 
}, 
bindScroll: function(id) { 
    window.addEventListener('scroll', this.updateContainer.bind(this,id), false); 
} 

所以可以这样做:

instance.bindScroll("testcontainer"); 

注:x和z不能现场所以您可以重新加载值...


如果添加更多和更多的功能,你的代码可能难以管理。你可以使用继承和构造函数来代替:

function instance(id){ 
this.el=document.querySelector(id); 
} 
instance.prototype={ 
bindScroll:function(){ 
    window.addEventListener("scroll",this.update.bind(this),false); 
    return this; 
    }, 
    update: function() { 
    var container = this.el; 
    container.style.position = 'absolute'; 
    container.style.width = x + 'px'; 
    container.style.minHeight = z + 'px'; 
    return this; 
} 
}; 

所以,你可以这样做:

var test=new instance("#test") 
test.update().bindScroll(); 
+0

非常感谢。 是否有可能将此代码转换为一个正在运行的实例? 我应该补充说,这应该是一个广告模板,它从第三方服务器注入到网站的DOM中。 – AppRoyale

+0

@AppRoyale即时在一个* StackSnippets不支持*设备...所以我可以做我当我 –

+0

这将是伟大的,高度赞赏。 – AppRoyale