如何将多个事件(调整大小和加载)绑定到addEventListener

时间:2016-08-31 12:56:01

标签: javascript

谷歌搜索,但找不到我的问题的正确答案。网上有一些解决方案只是有用的,我需要改变我的整个代码结构,这不是我想要的。



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;
&#13;
&#13;

2 个答案:

答案 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";
                }
              }
            })
        });
    }
}