简体   繁体   中英

Using jQuery to scroll to the top of a clicked div

I've searched the web at length for a solution and come very close, but I'm hoping someone smarter than I can perfect this. When I click a div, I would like the top of said div to scroll to the top of the browser window. The current code snippet causes a parent div with the id "centered" to scroll to the top, but I would like each child div to scroll to its own top without having to write out an instance for every single div.

toggle:function(divid){ //public method
if (typeof divid=="object")
    divid=divid[0]
this.showhide(divid, "toggle")
$("html, body").animate({scrollTop:$('#centered').position().top}, 600);

}

Can anyone point out what I'm missing?

Without knowing what 'divid' represents, this is a fairly generic example that probably won't directly fit your scenario. However, assuming 'divid' is the id value or an object representing the div you should be able to do something like this:

toggle:function(divid) {
    if (typeof divid == 'object') {
        divid = $(divid[0]); // Assumes a jQuery object (not very robust)
    } else {
        divid = $('#' + divid);
    }

    this.showhide(divid, "toggle"); // May break depending if it accepts the jQuery object
    $('html, body').animate({ scrollTop: divid.offset().top }, 600);
}

If 'this' is a reference to the div in question you can just swap in $(this) instead of using divid.

Note this code is not very robust so should be correctly altered to account for whatever divid really is. Also note - don't forget your semi-colons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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