我试图理解如何将参数传递给forEach.call
内的函数。我基本上将我的代码转换为对象文字,并且当我稍后添加更多动画时,将函数拆分为更干燥。
问题是,它在加载时记录元素但在此之后不再记录,我猜它是因为变量在第一个日志之后不再存在。我将如何使其发挥作用,或者方法是完全错误和无意义的?
工作示例: https://codepen.io/HendrikEng/pen/aEKPmM?editors=1010
我干涸的尝试: https://codepen.io/HendrikEng/pen/XVBpPV?editors=0011
const who = {
trigger: [...document.getElementsByClassName('slide')],
init: () => {
console.log('init');
who.trigger.forEach.call(who.trigger, (el) => {
el.addEventListener('mouseover', who.animateOver(el), false);
});
who.trigger.forEach.call(who.trigger, (el) => {
el.addEventListener('mouseout', who.animateOut(el), false);
});
},
animateOver: (el) => {
console.log('animateOver');
console.log(el);
// animate image
const image = el.getElementsByClassName("img")[0];
TweenMax.to(image, 0.25, {
yPercent: 35,
ease: Power1.easeOut,
});
},
animateOut: (el) => {
console.log(el);
console.log('animateOut');
const image = el.getElementsByClassName('img')[0];
TweenMax.to(image, 0.75, {
yPercent: 0,
ease: Bounce.easeOut,
});
},
debug: () => {
console.log('debug');
},
destroy() {
console.log('destroy');
},
};
who.init();
答案 0 :(得分:2)
Question的代码调用.addEventListener()
设置的函数,而不是在调度事件时引用要调用的函数。此外,该事件已附加到<img>
元素,无需.getElementsByClassName()
调用
const who = {
trigger: [...document.getElementsByClassName('slide')],
init: () => {
console.log('init');
who.trigger.forEach.call(who.trigger, (el) => {
el.addEventListener('mouseover', who.animateOver, false);
});
who.trigger.forEach.call(who.trigger, (el) => {
el.addEventListener('mouseout', who.animateOut, false);
});
},
animateOver: (el) => {
console.log('animateOver');
console.log(el);
// animate image
const image = el.target;
console.log(image);
TweenMax.to(image, 0.25, {
transformStyle: 'preserve-3d',
yPercent: 35,
ease: Power1.easeOut,
});
},
animateOut: (el) => {
console.log(el);
console.log('animateOut');
const image = el.target;
TweenMax.to(image, 0.75, {
yPercent: 0,
ease: Bounce.easeOut,
});
},
debug: () => {
console.log('debug');
},
destroy() {
console.log('destroy');
},
};
onload = () => who.init();