Ignore parent onclick when child onclick is clicked, using Javascript only

前端 未结 2 914
挽巷
挽巷 2020-12-21 04:57

An good example of what im trying to do is, think of instragram. When you are click on a photo, it opens a window with that photo plus the grey background. If you click anyw

相关标签:
2条回答
  • 2020-12-21 05:07

    Avoid intrinsic event attributes (like onclick). Bind your event handlers with JavaScript. Take advantage of the event object to prevent further propagation of the event up the DOM (so it never reaches the parent and thus doesn't trigger the event handler bound to it).

    document.querySelector("div").addEventListener("click", parent);
    document.querySelector("div div").addEventListener("click", child);
    
    function parent(event) {
      console.log("Parent clicked");
    }
    
    function child(event) {
      event.stopPropagation();
      console.log("Child clicked");
    }
    div {
      padding: 2em;
      background: red;
    }
    
    div div {
      background: blue;
    }
    <div>
      <div>
      </div>
    </div>

    0 讨论(0)
  • 2020-12-21 05:20

    You perhaps can take an inner div which is absolute that has the background and certain height and width which is equal to main parent div and that has all the style, so on click of that div you may close parent div and on image you need not to do anything.

    <div Parent><div Childdiv>
    </div>
    <img>
    </div>
    

    So childdiv should have display none functionality. With JavaScript, you should be able to close parent div on a click of child div.

    0 讨论(0)
提交回复
热议问题