简体   繁体   English

JavaScript-跟踪滚动事件

[英]javascript - track scroll event

I have a rogue scroll event that keeps automatically scrolling my page to the top each time I load a div element using Ajax. 我有一个流氓滚动事件,每次使用Ajax加载div元素时,该事件都会自动将页面滚动到顶部。 How do I track this down? 我该如何追踪呢? I've tried setting breakpoint in scroll event handler and looking at callstack but that doesn't give me anything useful since it just shows it coming from jquery, but I am interested in knowing what event on what DOM element caused the scroll. 我试过在滚动事件处理程序中设置断点并查看调用栈,但这并没有提供任何有用的信息,因为它只是显示了来自jquery的断点,但我想知道哪个DOM元素上的哪个事件导致了滚动。

A little background, I am loading a div element using Ajax when a div element is clicked (onclick). 有点背景,单击div元素(onclick)时,我正在使用Ajax加载div元素。 NOTE this is not anchor!! 注意这不是锚! But whenever I am close or at the bottom of the page, after the div element is loaded and added to the page, the page scrolls all the way to the top. 但是,每当我关闭页面或在页面底部时,将div元素加载并添加到页面后,页面就会一直滚动到顶部。 Really annoying and trying to track down the element that initiated that rogue scroll... 确实很烦人,并试图找出引发该恶意滚动的元素...

Thank! 谢谢!

如果您不介意使用jQuery插件,请尝试查看Waypoint插件 ,此插件非常适合跟踪/处理滚动

If I've understood fine you need a code similar to this, in this code I show new data from ajax when the user is (through scroll) to a distance of 4000 pixels from the last element (in this case a div.newDeal:last) (was a very long web). 如果我很好理解,则需要与此类似的代码,在此代码中,当用户(通过滚动)到最后一个元素(在这种情况下为div.newDeal)达到4000像素的距离时,我将显示来自ajax的新数据:最后)(网络很长)。

$(document).ready(function() {

//global variable in this script to test if I already made the request ajax ( I dont 
//want to make continious ajax request)
var loaded=false;


$(window).bind('scroll', handlerScroll); //attach event to the scroll


})//end document ready

//FIRE AUTOSCROLL (FIRE REQUEST AJAX)
//*************************************

var handlerScroll=function (){

    //get position of the scroll
    var space=$('#listdeals div.newDeal:last').offset().top - $(window).scrollTop();
    //if that distance is less than (or the middle, or the bottom). fire the request ajax
    if  (space<= 4000  &&     jQuery('div.previousDeal').size()==0){  

        //disable scroll event
        $(window).unbind();



        //
        //build data post
        //
        var  parameters="actionAutoscroll=true&"+.........;

        //MAKE REQUEST AJAX
        //********************

        $.ajax({  
            url: "/offers",  
            type:'POST',  
            data: parameters,   
            success: process_previousDeals       
        });  //end ajax


        return false;

    }
}//end if  load previous deals depending of scroll

}//end handler


function process_previousDeals(results){
 //inject new content in the page
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM