How to add onload event to a div element

前端 未结 24 2250
谎友^
谎友^ 2020-11-22 00:26

How do you add an onload event to an element?

Can I use:

for t

24条回答
  •  礼貌的吻别
    2020-11-22 01:02

    Since the onload event is only supported on a few elements, you have to use an alternate method.

    You can use a MutationObserver for this:

    const trackElement = element => {
      let present = false;
      const checkIfPresent = () => {
        if (document.body.contains(element)) {
          if (!present) {
            console.log('in DOM:', element);
          }
          present = true;
        } else if (present) {
          present = false;
          console.log('Not in DOM');
        }
      };
    
      const observer = new MutationObserver(checkIfPresent);
      observer.observe(document.body, { childList: true });
      checkIfPresent();
    
      return observer;
    };
    
    const element = document.querySelector('#element');
    const add = () => document.body.appendChild(element);
    const remove = () => element.remove();
    
    trackElement(element);
    
    
    
    
    Element

提交回复
热议问题