How to add onload event to a div element

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

How do you add an onload event to an element?

Can I use:

for t

24条回答
  •  春和景丽
    2020-11-22 00:58

    First to answer your question: No, you can't, not directly like you wanted to do so. May be a bit late to answer, but this is my solution, without jQuery, pure javascript. It was originally written to apply a resize function to textareas after DOM is loaded and on keyup.

    Same way you could use it to do something with (all) divs or only one, if specified, like so:

    document.addEventListener("DOMContentLoaded", function() {
        var divs = document.querySelectorAll('div'); // all divs
        var mydiv = document.getElementById('myDiv'); // only div#myDiv
        divs.forEach( div => {
            do_something_with_all_divs(div);
        });
        do_something_with_mydiv(mydiv);
    });
    

    If you really need to do something with a div, loaded after the DOM is loaded, e.g. after an ajax call, you could use a very helpful hack, which is easy to understand an you'll find it ...working-with-elements-before-the-dom-is-ready.... It says "before the DOM is ready" but it works brillant the same way, after an ajax insertion or js-appendChild-whatever of a div. Here's the code, with some tiny changes to my needs.

    css

    .loaded { // I use only class loaded instead of a nodename
        animation-name: nodeReady;
        animation-duration: 0.001s;
    }
    
    @keyframes nodeReady {  
        from { clip: rect(1px, auto, auto, auto); }
        to { clip: rect(0px, auto, auto, auto); }  
    }
    

    javascript

    document.addEventListener("animationstart", function(event) {
        var e = event || window.event;
        if (e.animationName == "nodeReady") {
            e.target.classList.remove('loaded');
            do_something_else();
        }
    }, false);
    

提交回复
热议问题