如何将其他对象插入事件侦听器

how to insert other object to event listener?

本文关键字:插入 入事件 侦听器 对象 其他      更新时间:2023-09-26

我的javascript:

var tool = {
    addEvent : function(element, eventName, callback){
        if (element.addEventListener) {
            element.addEventListener(eventName, callback, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + eventName, callback);
        }          
    },
    getPosition : function(el){
        var _x = 0;
        var _y = 0;
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
            _x += el.offsetLeft - el.scrollLeft;
            _y += el.offsetTop - el.scrollTop;
            el = el.offsetParent;
        }
        return { top: _y, left: _x };
    }
}
function getObj(){
    this.a = document.getElementById('div');
    this.b = document.getElementById('table');

    this.func = function(){
        var pos = tool.getPosition(this);
        // how to insert this.b here
        // i want to set this.b offset from this.a offset
    }
    tool.addEvent(this.a,'scroll',this.func);
}
var obj = new getObj();

如何修改它。所以每当这个。A是滚动的。B会同步到这个。一个
这一点。B偏移量是从这里得到的。一个偏移量。

当我尝试:

 this.func = function(){
        var pos = tool.getPosition(this);
        // value from pos will be set to this.b
        console.log(this.b);
        // how to insert this.b here
        // i want to set this.b offset from this.a offset
 }

您的getPosition函数是this的成员,因此您不能使用getPosition(...)调用它。必须使用this.getPosition(...)调用它,或者将getPosition函数重新声明为函数作用域变量:

function getObj() {
    ...
    var getPosition = function(...) { ... };
    this.addEvent = function(...) { ... };
    ...
}
编辑:

当添加DOM事件时,您还需要将this.func绑定到当前上下文:

this.func = this.func.bind(this);

this.addEvent (this.a"滚动",this.func);