How to pass click events from one div to another?

前端 未结 3 715
攒了一身酷
攒了一身酷 2021-01-05 09:43

I need to find a way to pass click events from a div on top to the div below it (and ignore the clicks on the higher div). There is a known way of simulating the cli

3条回答
  •  时光取名叫无心
    2021-01-05 09:57

    You can trigger click event on one div, by clicking on another div.

    You can create an event a click event like

    //A function to fire an event
    function eventFire(el, etype){
        if (el.fireEvent) {
          el.fireEvent('on' + etype);
        } else {
          var evObj = document.createEvent('cClick');
          evObj.initEvent(etype, true, false);
          el.dispatchEvent(evObj);
        }
    }
    
    var div1 = document.getElementByID("firstDiv"); //find the first div
    div1.onClick = function() { //attach a onclick event
       //Now select the element and fire the event
       var div2 = document.getElementById("seconddiv"); //select the second div
       eventFire(div2, 'click'); //fire the click event
    };
    

提交回复
热议问题