您好我有以下代码来控制图片库的位置(可以在steven.tlvweb.com上看到)。滚轮当前控制画廊位置,但keydown事件没有,我希望他们。可以看到下面代码中的警报(keyLeft和keyRight),但根本没有调用 this.parent.scroll 。
参数sc只需要是一个正整数或负整数 - 这就是event.wheelDelta毕竟是什么所以我想知道,请问这个原型函数的正确方法是什么?
/* //////////// ==== ImageFlow Constructor ==== //////////// */
function ImageFlow(oCont, xmlfile, horizon, size, zoom, border, start, interval) {
this.oc = document.getElementById(oCont);
this.scrollbar = getElementsByClass(this.oc, 'div', 'scrollbar');
this.text = getElementsByClass(this.oc, 'div', 'text');
this.bar = getElementsByClass(this.oc, 'img', 'bar');
this.arL = getElementsByClass(this.oc, 'img', 'arrow-left');
this.arR = getElementsByClass(this.oc, 'img', 'arrow-right');
this.bar.parent = this.oc.parent = this;
this.arL.parent = this.arR.parent = this;
/* === handle mouse scroll wheel === */
this.oc.onmousewheel = function () {
this.parent.scroll(event.wheelDelta);
return false;
}
var pleasework = this;
/* ==== add keydown events ==== */
window.document.onkeydown=function(){
pleasework.keypress(event.keyCode);
return false;
}
}
/* //////////// ==== ImageFlow prototype ==== //////////// */
ImageFlow.prototype = {
scroll: function (sc) {
if (sc < 0) {
if (this.view < this.NF - 1) this.calc(1);
} else {
if (this.view > 0) this.calc(-1);
}
},
keypress : function (kp) {
switch (kp) {
case 39:
//right Key
if (this.view < this.NF - 1) this.calc(1);
break;
case 37:
//left Key
if (this.view > 0) this.calc(-1);
break;
}
},
}
提前致谢 Steven(新手Java程序员)
答案 0 :(得分:0)
不要在DOM元素上使用parent
属性。相反,只需在局部变量上创建一个闭包。所以,替换
this.bar.parent = this.oc.parent = this;
this.arL.parent = this.arR.parent = this;
/* === handle mouse scroll wheel === */
this.oc.onmousewheel = function () {
this.parent.scroll(event.wheelDelta);
return false;
}
/* ==== add keydown events ==== */
window.document.onkeydown=function(){
this.parent.keypress(event.keyCode);
return false;
}
与
var parent = this;
this.oc.onmousewheel = function(e) {
parent.scroll(e.wheelDelta);
e.preventDefault();
};
window.document.onkeydown = function(e) { // notice this overwrites previous listeners
parent.keypress(e.keyCode);
};