Bind scroll Event To Dynamic DIV?

前端 未结 9 1415
死守一世寂寞
死守一世寂寞 2020-12-11 16:23

For example, after using AJAX, I\'ll have a scrollable DIV. How to bind scroll events to it?

I\'ve tried:

$(window).on(\"scroll\", \".mydiv\", functi         


        
9条回答
  •  情话喂你
    2020-12-11 16:49

    In my app, I have a button that appends form fieldsets to the body every time a button is clicked - I wanted to scroll the page down to the new element, but that didn't work for obvious reasons (bubbling, etc.). I came up with a simple fix...

    function scroll(pixels){
        $('html, body').animate({
            scrollTop: pixels
        }, 1000);
    };
    
    function addObservation(x){
        $('body').append(x);
        newFieldSet = $('fieldset').last();
        pixelsFromTop = newFieldSet.offset().top;
        scroll(pixelsFromTop);
    };
    
    $(document).on("click", "#add_observation", function(){
        addObservation("
    SOME FORM FIELDS HERE
    "); });

    So every time you add a fieldset, jQuery finds the last one added, then .offset().top measures how many pixels the fieldset is from the top and then scrolls the window that distance.

提交回复
热议问题