谷歌搜索,但找不到我的问题的正确答案。网上有一些解决方案只是有用的,我需要改变我的整个代码结构,这不是我想要的。
window.addEventListener('DOMContentLoaded', function(event) {
if(window.matchMedia("(min-width: 767px)").matches){
Array.prototype.slice.call(document.getElementsByClassName("tabcontent")).forEach(function(element, index) {
element.addEventListener("mouseleave", function(event) {
event.target.style.display = "none";
});
document.getElementById("categories-list-box").addEventListener("mouseleave", function(event) {
if (event.relatedTarget.className.indexOf("tabcontent") == -1) {
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
}
})
});
}
})
&#13;
答案 0 :(得分:0)
function addListenerMulti(el, s, fn) {
s.split().forEach(e => el.addEventListener(e, fn, false));
}
和用法:
addListenerMulti(window, 'mousemove touchmove', function(){…});
答案 1 :(得分:0)
将代码放在函数中,并使用addEventListener
调用它window.addEventListener('DOMContentLoaded', myFunction);
window.addEventListener('resize', myFunction);
function myFunction(){
if(window.matchMedia("(min-width: 767px)").matches){
Array.prototype.slice.call(document.getElementsByClassName("tabcontent")).forEach(function(element, index) {
element.addEventListener("mouseleave", function(event) {
event.target.style.display = "none";
});
document.getElementById("categories-list-box").addEventListener("mouseleave", function(event) {
if (event.relatedTarget.className.indexOf("tabcontent") == -1) {
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
}
})
});
}
}