我的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);