在克里斯·费迪南迪(ChrisFerdinandi)的"Go Make Great Things" blog上,有一篇很棒的文章介绍了如何从jQuery库中创建.on()
方法的“ Vanilla JS”版本。
var on = function (event, elem, callback, capture) {
if (typeof (elem) === 'function') {
capture = callback;
callback = elem;
elem = window;
}
capture = capture ? true : false;
elem = typeof elem === 'string' ? document.querySelector(elem) : elem;
if (!elem) return;
elem.addEventListener(event, callback, capture);
};
我是否因为需要addEventListener
使用字符串来设置冒泡或捕获而需要三元或某些条件吗?
capture = capture ? true : false;
capture = capture === true ? 'true' : 'false';
所以我试图利用上面的代码来创建过渡,但是我得到了,
Uncaught TypeError: Failed to execute 'addEventListener' on 'EventTarget': The callback provided as parameter 2 is not an object.
这是标记:
<a href = "#">
<img class="make-up-img color-palette" alt="Eyes on you - Color Palette"
src="https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink$" />
</a>
这是脚本:
var on = function(event, elem, callback, capture) {
if (typeof elem === 'function') {
capture = callback;
callback = elem;
elem = window;
}
console.log(capture)
capture = capture ? true : false;
capture = capture === true ? 'true' : 'false';
console.log(capture)
elem = typeof elem === 'string' ? document.querySelector(elem) : elem;
if (!elem) return;
elem.addEventListener(event, callback, capture);
};
function rollOver(elem){
if (document.querySelector(elem).getAttribute('src', 'https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink')) {
return document.querySelector(elem).getAttribute('src', 'https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink')
}
return document.querySelector(elem).getAttribute('src', 'https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink');
}
on('mouseover', '.color-palette', rollOver('.color-palette'));